129. Sum Root to Leaf Numbers

题目如上,二叉树由根到节点上的值可以组成一个数字,该题是要求所有由根到最终节点的所有路径上的数字进行求和。

解题的主要思路是使用前序遍历,以前面节点的值乘以10再加上当前值的形式进行数字组合,当到达树叶结点的时候总和加上组建好的路径的值。

代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     
12     private int sum = 0;
13 
14     public int sumNumbers(TreeNode root) {
15     
16         helper(root,0);
17         
18         return sum;
19     }
20     
21     private void helper(TreeNode root, int num){
22         if(root == null){
23             return;
24         }
25         
26         num = num*10 + root.val;
27         if(root.left != null ){
28             helper(root.left, num);
29         }
30         
31         if(root.right != null ){
32             helper(root.right, num);
33         }
34         
35         if(root.right == null && root.left == null){
36             sum += num;
37         }
38     }
39 }

END

原文地址:https://www.cnblogs.com/sssysukww/p/8793958.html