/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
LinkedList<Integer> resList = new LinkedList<Integer>();
sumRoot2Leaf(root,0,resList);
int res = 0;
for(Integer i:resList){
res+=i;
}
return res;
}
public void sumRoot2Leaf(TreeNode root, int res, LinkedList<Integer> resList){
if(root == null) return;
if(root.left == null && root.right == null){
res = res * 10 + root.val;
resList.add(res);
return;
}
sumRoot2Leaf(root.left,res*10 + root.val,resList);
sumRoot2Leaf(root.right,res*10 + root.val,resList);
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
Thursday, August 14, 2014
Sum Root to Leaf Numbers
This question is not difficult. Based on DFS, value of each node is stored and summed up until leaf node is met. Once hit the leaf node, add value of this node, then add this result to resList. As soon as the whole tree is traversed, sum up all the elements in resList. Then we get what we want.
Labels:
LeetCode
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment