129. Sum Root to Leaf Numbers pathsum路径求和

[抄题]:

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.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
    1
   / 
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1]
    4
   / 
  9   0
 / 
5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

dfs的参数写错:sum由于经常要操作 而且需要返回,所以放在里面不用拿出来。

左右dfs的前提是root.l/r非空,空了就返回。所以空不空是一个重要判断条件

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. sum = 0必须写在dfs里,每次重置为0。不然每次dfs会出现重复加的毛病。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

sum由于经常要操作 而且需要返回,所以放在里面不用拿出来。

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

class Solution {  
    public int sumNumbers(TreeNode root) {
        //corner case
      if (root == null) return 0;
      //return
      return dfs(root, 0);
    }
  
  public int dfs(TreeNode root, int cur) {
    //exit if left and right are null
    if (root.left == null && root.right == null) return cur * 10 + root.val;
    
    //if not null, go left / right
    int sum = 0;
    if (root.left != null) sum += dfs(root.left, cur * 10 + root.val);
    if (root.right != null) sum += dfs(root.right, cur * 10 + root.val);
    
    //return
    return sum;
  }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9460293.html