Sum root to leaf numbers

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number.

  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bitinteger.

A leaf node is a node with no children.

class Solution {
int rootToLeaf = 0;

public void preorder(TreeNode r, int currNumber) {
if (r != null) {
currNumber = (currNumber * 10) + r.val;
// if it's a leaf, update root-to-leaf sum
if (r.left == null && r.right == null) {
rootToLeaf += currNumber;
}
preorder(r.left, currNumber);
preorder(r.right, currNumber);
}
}
public int sumNumbers(TreeNode root) {
preorder(root, 0);
return rootToLeaf;
}
}

Sum of Root To Leaf Binary Numbers

You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits integer.

class Solution {
int rootToLeaf = 0;

public void preorder(TreeNode r, int currNumber) {
if (r != null) {
currNumber = (currNumber << 1) | r.val;
// if it's a leaf, update root-to-leaf sum
if (r.left == null && r.right == null) {
rootToLeaf += currNumber;
}
preorder(r.left, currNumber);
preorder(r.right, currNumber);
}
}
public int sumRootToLeaf(TreeNode root) {
preorder(root, 0);
return rootToLeaf;
}
}