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 }

 

相关文章:

  • 2021-06-04
  • 2021-12-09
  • 2022-12-23
  • 2021-11-21
  • 2021-12-30
  • 2022-03-02
  • 2021-07-19
猜你喜欢
  • 2022-01-11
  • 2021-07-11
  • 2021-06-09
  • 2021-08-03
  • 2021-07-04
  • 2021-10-01
  • 2022-02-02
  • 2021-11-03
相关资源
相似解决方案