Here is the problem (It's on LeetCode)
Here is my code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private static List<String> list = new LinkedList<String>();
public int sumNumbers(TreeNode root) {
serachBinaryTreeRecursion(root, "");
int result = 0;
for(String i : list){
result += Integer.valueOf(i);
}
return result;
}
public void serachBinaryTreeRecursion(TreeNode root, String path) {
if (root == null) {
return;
}
if (root.left != null) {
serachBinaryTreeRecursion(root.left, path + String.valueOf(root.val));
}
if (root.right != null) {
serachBinaryTreeRecursion(root.right, path + String.valueOf(root.val));
}
if (root.left == null && root.right == null) {
list.add((path + String.valueOf(root.val)));
}
}
}
When I submit this,it reports errors.
I test on eclipse,the result is correct.
What's wrong with my code?
Why are you doing String.valueOf(root.val)
? That is converting your int variable to string and adding 0 to 1 as string, not as integer, hence wrong result.
For [0, 1]
you seem to have constructed a tree 1 -> (0, -)
instead of 0 -> (-, 1)
. Hence 10 instead of 1. So the algorithm did function.
Operation successful, patient dead.
(Please no "serach..." too.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.