Sum Root to Leaf

  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
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;
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

GPIO Pins (User manual Read-along)

CAP Theorem

Elixir vs Ruby: Which is Faster?

Why Sleep Is the Most Underrated? Tool Becouse for Good Health, Longevity, and Productivity

L2 Hackathon Countdown | $110K PRIZES on Lit; Ready to Scale!

Liferay Enterprise Portal Software — A Hot Topic of Discussion

Year of the Occam

L2 Wars — Why we chose to build on StarkNet?

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
Abhinay Gupta

Abhinay Gupta

More from Medium

Deconstructing Data Structures: Linked List

HackerRank 30 Days of Code: Day 10 — Binary Numbers

Everyday Things: Binary Search Trees & the Recursive Search Algorithm

The Linked List Data Structure