Sum Root to Leaf

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;
}
}
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;
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store