Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created August 11, 2013 21:46
Show Gist options
  • Save charlespunk/6206994 to your computer and use it in GitHub Desktop.
Save charlespunk/6206994 to your computer and use it in GitHub Desktop.
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumNumbers(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
int[] sum = new int[1];
dfs(0, sum, root);
return sum[0];
}
public void dfs(int one, int[] sum, TreeNode root){
if(root == null) return;
one = one * 10 + root.val;
if(root.right == null && root.left == null){
sum[0] += one;
return;
}
if(root.right != null) dfs(one, sum, root.right);
if(root.left != null) dfs(one, sum, root.left);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment