题目描述
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 static int sumNumbers(TreeNode root) {
int result = 0;
if (root == null)
return result;
if (root.left == null && root.right == null)
return root.val;
Stack<Integer> stackVal = new Stack<Integer>();
Stack<TreeNode> stackNode = new Stack<TreeNode>();
TreeNode tempNode;
int tempVal;
stackVal.add(root.val);
stackNode.add(root);
while (!stackNode.isEmpty()) {
tempNode = stackNode.pop();
tempVal = stackVal.pop();
if (tempNode.left == null && tempNode.right == null) {
result += tempVal;
} else {
if (tempNode.left != null) {
stackNode.add(tempNode.left);
stackVal.add(tempVal * 10 + tempNode.left.val);
}
if (tempNode.right != null) {
stackNode.add(tempNode.right);
stackVal.add(tempVal * 10 + tempNode.right.val);
}
}
}
return result;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}