首页 > 技术文章 > 129.Sum Root to Leaf Numbers

cing 2018-04-12 11:11 原文

题目链接

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

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

 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

 

推荐阅读