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
public class Solution { public int sumNumbers(TreeNode root) { return sum(root, 0); } public int sum(TreeNode root, int sum){ if(root == null) return 0; sum = 10 * sum + root.val; if(root.left == null && root.right == null){//forgot to check no child return sum; } return sum(root.left, sum) + sum(root.right, sum); } }
mistakes: when no child, return sum directly
public class Solution { public int sumNumbers(TreeNode root) { Stack<TreeNode> nodeStack = new Stack<TreeNode>(); Stack<Integer> sumStack = new Stack<Integer>(); TreeNode node = root; int prePathSum = 0, sum = 0; while(node!=null||!nodeStack.empty()) { while(node!=null) { prePathSum = (prePathSum * 10) + node.val; nodeStack.push(node); sumStack.push(prePathSum); node = node.left; } if(!nodeStack.empty()) { node = nodeStack.pop(); prePathSum = sumStack.pop(); // check whether it is a leaf node if(node.left==null&&node.right==null) { sum += prePathSum; } // go to its right node node = node.right; } } return sum; } }