Created
August 11, 2013 21:46
-
-
Save charlespunk/6206994 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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