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
.
Solution in Java 1: 后序遍历+非递归
<span style="font-size:18px;">/**
* Definition for a binary tree node.
* 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;
int sum = 0;
int curSum =0;
int digit = 0;
Stack<TreeNode> path = new Stack<TreeNode>();
Stack<Boolean> ifVisited = new Stack<Boolean>();
while(root!=null || !path.empty()){
while(root!=null){
curSum = curSum*10+root.val;
digit++;
path.push(root);
ifVisited.push(false);
root = root.left;
}
//loop until root is null, there is no left child;
while(ifVisited.peek()&&!ifVisited.empty()){
}
if(!path.empty()){
TreeNode curNode = path.peek();
if(curNode.right==null && curNode.left==null){ //no left child and no right child=> leafnode
path.pop();
ifVisited.pop();
sum = sum+ curSum;
curSum = curSum/10;
digit--;
}
else{
if(ifVisited.peek()){ //the top node has already been visited the right subtree
path.pop();
ifVisited.pop();
curSum= curSum/10;
digit--;
}
else{
ifVisited.pop();
ifVisited.push(true);
root = curNode.right;
}
}
}
}
return sum;
}
}</span>
Note: 必须要用后续遍历,是因为如果是前序或者中序,在未遍历右子树的时候,保存之前路径的信息(包括该右子树的根结点信息,值等)就要被更新了,在该题中就行不通的。
Solution in Jav
a 2: 递归的方法
<span style="font-size:18px;">/**
* Definition for a binary tree node.
* 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;
return getSum(root, 0);
}
public int getSum(TreeNode root, int cur){
if(root.left==null&& root.right==null) return cur*10+root.val;
int result =0;
if(root.left!=null) result+=getSum(root.left, cur*10+root.val);
if(root.right!=null) result+=getSum(root.right, cur*10+root.val);
return result;
}
}</span>