zoukankan      html  css  js  c++  java
  • Leetcode: Sum Root to Leaf Numbers

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
    
    An example is the root-to-leaf path 1->2->3 which represents the number 123.
    
    Find the total sum of all root-to-leaf numbers.
    
    For example,
    
        1
       / 
      2   3
    The root-to-leaf path 1->2 represents the number 12.
    The root-to-leaf path 1->3 represents the number 13.
    
    Return the sum = 12 + 13 = 25.

    主要是看你如何设计这个Recursion 这是一道树的题目,一般使用递归来做,主要就是考虑递归条件和结束条件。想到这样设计Recursion其实还挺难的

     1 public class Solution {
     2     public int sumNumbers(TreeNode root) {
     3         if (root == null) return 0;
     4         return helper(root, 0);
     5     }
     6     
     7     public int helper(TreeNode root, int sum) {
     8         if (root.left==null && root.right==null) return 10*sum+root.val;
     9         else if (root.left == null) return helper(root.right, 10*sum+root.val);
    10         else if (root.right == null) return helper(root.left, 10*sum+root.val);
    11         else {
    12             return helper(root.left, 10*sum+root.val) + helper(root.right, 10*sum+root.val);
    13         }
    14     }
    15 }

    推荐做法:

     1 public int sumNumbers(TreeNode root) {
     2     return helper(root,0);
     3 }
     4 private int helper(TreeNode root, int sum)
     5 {
     6     if(root == null)
     7         return 0;
     8     if(root.left==null && root.right==null)
     9         return sum*10+root.val;
    10     return helper(root.left,sum*10+root.val)+helper(root.right,sum*10+root.val);
    11 }
  • 相关阅读:
    利用Tomcat搭一个原型图服务器
    Linux 安装Nginx
    Linux 数据库安装
    一点点感慨
    文件锁-fcntl flock lockf
    Linux生成core文件、core文件路径设置
    信号量 互斥量 读写锁 条件变量
    二叉树遍历
    UNIX网络编程——常用服务器模型总结
    hash_map
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3984158.html
Copyright © 2011-2022 走看看