Description:
Given a tree, each node with a value, and we need to calculate the sum of all the number from leaf to root.
Solution:
Just a dfs is enough.
/**
* Definition for binary tree public class TreeNode { int val; TreeNode left;
* TreeNode right; TreeNode(int x) { val = x; } }
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
int ans = 0;
public int sumNumbers(TreeNode root) {
ans = 0;
dfs(root, 0);
return ans;
}
void dfs(TreeNode root, int num) {
if (root.left != null)
dfs(root.left, num * 10 + root.val);
if (root.right != null)
dfs(root.right, num * 10 + root.val);
else if (root.left == null)
ans += num * 10 + root.val;
}
}