Sum Root to Leaf Numbers
Total Accepted: 43960 Total Submissions: 144900My Submissions
Question Solution
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) {
if(root==null)
return 0;
TreeNode x=root;
Stack<TreeNode> stack=new Stack<TreeNode>();
int sum=0;
int path=0;
stack.push(x);
path=path*10+x.val;
while(!stack.isEmpty()){
TreeNode y=stack.peek();
//stack.pop();
if(y.left!=null)
{
TreeNode z=y.left;
y.left=null;
stack.pop();
stack.push(y);
stack.push(z);
path=path*10+z.val;
}
else if(y.right!=null)
{
TreeNode z=y.right;
y.right=null;
stack.pop();
stack.push(y);
stack.push(z);
path=path*10+z.val;
}
else
{
sum=sum+path;
while(!stack.isEmpty())
{
TreeNode z=stack.peek();
if(z.left==null&&z.right==null)
{
path=path/10;
stack.pop();
}
else
break;
}
}
}
return sum;
}
}