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

Illegal Argument Exception in Java

Extended trial coupons for Woocommerce

Build Serverless App & CI/CD pipeline w/ AWS SAM & GitHub Actions

Should you Make the Shift to Microservices Architecture in the Age of Digital Transformation?

-Music And Programming

Derived Fact Types in Object-Role Modeling

The Rationale of Rust

Constructors in Java

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

Divide and Conquer vs Greedy Algorithms.

[Leet Code] Maximum Number of Words Found in Sentences

Getting started with data structures and algorithms?

An Introduction to Linked Lists