Sum Root to Leaf Numbers Java
2014-07-30 15:03
405 查看
Given a binary tree containing digits from
each root-to-leaf path could represent a number.
An example is the root-to-leaf path
the number
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
Check the coding below in detail:
/*
Key to solve: Recursion + DFS
1.construct num=num*10+value every Tree level down
2.return sum when reach the bottom of tree
3.recursively through the TreeNode by DFS Traversal
*/
public class Solution {
public int sumNumbers(TreeNode root) {
return helperDFS(root,0,0);
}
private int helperDFS(TreeNode root, int num , int sum){
//base case
if(root==null) return 0;
num=num*10+root.val;
//check for reach the bottom
if(root.left==null && root.right==null){
sum+=num;
return sum;
}
return helperDFS(root.left,num,sum)+helperDFS(root.right,num,sum);
}
}
0-9only,
each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path
1->3represents the number
13.
Return the sum = 12 + 13 =
25.
Check the coding below in detail:
/*
Key to solve: Recursion + DFS
1.construct num=num*10+value every Tree level down
2.return sum when reach the bottom of tree
3.recursively through the TreeNode by DFS Traversal
*/
public class Solution {
public int sumNumbers(TreeNode root) {
return helperDFS(root,0,0);
}
private int helperDFS(TreeNode root, int num , int sum){
//base case
if(root==null) return 0;
num=num*10+root.val;
//check for reach the bottom
if(root.left==null && root.right==null){
sum+=num;
return sum;
}
return helperDFS(root.left,num,sum)+helperDFS(root.right,num,sum);
}
}
相关文章推荐
- sum-root-to-leaf-numbers Java code
- [Leetcode][JAVA] Sum Root to Leaf Numbers
- java-Sum Root to Leaf Numbers
- Java for LeetCode 129 Sum Root to Leaf Numbers
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(全部根到叶子结点组组成的数字相加)】
- Sum Root to Leaf Numbers (Java)
- [LeetCode][Java] Sum Root to Leaf Numbers
- leetcode:Sum Root to Leaf Numbers 【Java】
- leetcode129 Sum Root to Leaf Numbers java 算法
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(所有根到叶子结点组组成的数字相加)】
- [Leetcode] Sum Root to Leaf Numbers (Java)
- Sum Root to Leaf Numbers leetcode java
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- [leetcode] Sum Root to Leaf Numbers
- leetcode Sum Root to Leaf Numbers 二叉树所有叶节点的路径和
- LeetCode: Sum Root to Leaf Numbers
- [LEETCODE] Sum Root to Leaf Numbers
- 【leetcode】Sum Root to Leaf Numbers
- [Leetcode]Sum Root to Leaf Numbers