Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/SumNumbers.java Secret
Created Jun 12, 2017

Embed
What would you like to do?
Sum Numbers
package com.interviewbytes.trees;
public class SumNumbers {
private int totalSum = 0;
public int sumNumbers(TreeNode root) {
helper(root, 0);
return totalSum;
}
private void helper(TreeNode node, int sum) {
if (node == null) return;
sum = sum * 10 + node.val;
if (node.left == null && node.right == null) {
totalSum = totalSum + sum;
return;
}
helper(node.left, sum);
helper(node.right, sum);
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.