Created
March 5, 2013 04:55
-
-
Save daifu/5088108 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.
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. | |
| */ | |
| /** | |
| * Definition for binary tree | |
| * public class TreeNode { | |
| * int val; | |
| * TreeNode left; | |
| * TreeNode right; | |
| * TreeNode(int x) { val = x; } | |
| * } | |
| */ | |
| public class Solution { | |
| ArrayList<ArrayList<Integer>> set = new ArrayList<ArrayList<Integer>>(); | |
| public int sumNumbers(TreeNode root) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if(root == null) return 0; | |
| set.clear(); | |
| ArrayList<Integer> arys = new ArrayList<Integer>(); | |
| getPathNumbers(arys, root); | |
| ArrayList<Integer> arySum = new ArrayList<Integer>(); | |
| for(int i = 0; i < set.size(); i++) { | |
| arySum.add(buildNum(set.get(i))); | |
| } | |
| int ret = 0; | |
| for(int i = 0; i < arySum.size(); i++) { | |
| ret += arySum.get(i); | |
| } | |
| return ret; | |
| } | |
| public void getPathNumbers(ArrayList<Integer> arys, TreeNode root) { | |
| if(root.left == null && root.right == null) { | |
| arys.add(root.val); | |
| set.add(new ArrayList<Integer>(arys)); | |
| } else { | |
| arys.add(root.val); | |
| if(root.left != null) { | |
| getPathNumbers(arys, root.left); | |
| arys.remove(arys.remove(arys.size() - 1)); | |
| } | |
| if(root.right != null) { | |
| getPathNumbers(arys, root.right); | |
| arys.remove(arys.remove(arys.size() - 1)); | |
| } | |
| } | |
| } | |
| public int buildNum(ArrayList<Integer> list) { | |
| int sum = 0; | |
| for(int i = 0; i < list.size(); i++) { | |
| sum = sum * 10 + list.get(i); | |
| } | |
| return sum; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No working for "{2,1,#,4,#,7,#,4,#,8,#,3,#,6,#,4,#,7}";