Created
February 15, 2015 21:17
-
-
Save dmnugent80/49d6939594a7389b1d7c to your computer and use it in GitHub Desktop.
Sum Root to Leaf Numbers
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) { | |
return sumNumbersHelper(root, 0); | |
} | |
public int sumNumbersHelper(TreeNode node, int path){ | |
if (node == null) return 0; | |
path = path*10 + node.val; | |
if (node.left == null && node.right == null) return path; | |
int left = 0; | |
int right = 0; | |
if (node.left != null){ | |
left = sumNumbersHelper(node.left, path); | |
} | |
if (node.right != null){ | |
right = sumNumbersHelper(node.right, path); | |
} | |
return (left + right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment