129.Sum Root to Leaf Numbers

题目连接ide

题目大意:给出一个二叉树,从根节点到叶的路径上的数值组成一个int型的数值,将全部路径上的全部数值相加获得最总和。例子以下:spa

法一:DFS。从根节点到叶节点,在路径上每到达一个节点,则计算出其值,而后DFS进去便可。代码以下(耗时1ms):3d

 1     public int sumNumbers(TreeNode root) {
 2         if(root == null) {
 3             return 0;
 4         }
 5         int res = 0;
 6         res = dfs(root, 0, res);
 7         return res;
 8     }
 9     private static int dfs(TreeNode root, int cnt, int res) {
10         //计算最后叶节点的数值,因为前面有判断进来的节点是否为null,因此这里root必定是非空节点
11         if(root.left == null && root.right == null) {
12             res += cnt * 10 + root.val;
13             return res;
14         }
15         //计算根节点的数值
16         cnt = cnt * 10 + root.val;
17         //若是有左孩子,遍历左孩子
18         if(root.left != null) {
19             res = dfs(root.left, cnt, res);
20         }
21         //若是有右孩子,遍历右孩子
22         if(root.right != null) {
23             res = dfs(root.right, cnt, res);
24         }
25         return res;
26     }
View Code
相关文章
相关标签/搜索