二叉树,每个节点的值是0~9的数字,
根到叶子节点的路径上代表了一个数字。
求所有根到叶子路径上的数字之和。
思路:
可能会想到DFS,但是二叉树的DFS和前序遍历其实是差不多的。
遍历应该是从root到leaf的,从上而下,
每遍历到一个节点,用高位的数值+root.val,
然后遍历root.left, root.right,
直到到了leaf, 把整个数字加到sum里面。
所以用到了树的前序遍历。
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
preOrder(root, 0);
return sum;
}
void preOrder(TreeNode root, int cur){
if(root == null) return;
cur = cur * 10 + root.val;
if(root.left == null && root.right == null) {
sum += cur;
}
preOrder(root.left, cur);
preOrder(root.right, cur);
}
}