leetcode------Sum Root to Leaf Numbers
标题: | Sum Root to Leaf Numbers |
通过率: | 30.4% |
难度: | 中等 |
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
.
整个过程是深度优先,然后每下一层就放大十倍,那么如果是叶子节点则与sum相加,其他时候继续往下搜索,代码如下:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 int sum; 12 public int sumNumbers(TreeNode root) { 13 sum=0; 14 if(root==null)return 0; 15 dfs(root,0); 16 return sum; 17 } 18 public void dfs(TreeNode root,int num){ 19 num=num*10+root.val; 20 if(root.right==null&&root.left==null) sum+=num; 21 if(root.left!=null) dfs(root.left,num); 22 if(root.right!=null) dfs(root.right,num); 23 24 } 25 }