1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int sumRootToLeaf(TreeNode root) { return dfs(root, 0); }
private int dfs(TreeNode root, int prefix) { if (root == null) { return 0; }
prefix = (prefix << 1) + root.val; if (root.left == null && root.right == null) { return prefix; } return dfs(root.left, prefix) + dfs(root.right, prefix); } }
|
References
1022. Sum of Root To Leaf Binary Numbers