All four traversals require O(n) time as they visit every node exactly once.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
return cal(root, 0);
}
private int cal(TreeNode root, int sum) {
if (root == null) return 0;
int currentSum = sum*10 + root.val;
if (root.left == null && root.right == null) return currentSum;
int leftSum = cal(root.left, currentSum);
int rightSum = cal(root.right, currentSum);
return leftSum + rightSum;
}
}