Java 根数与叶数之和

Java 根数与叶数之和,java,algorithm,tree,binary-tree,Java,Algorithm,Tree,Binary Tree,这是在LeetCode上的 这是我的密码: /** * 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<St

这是在LeetCode上的

这是我的密码:

/**
 * 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)));
        }
    }
}
当我提交此文件时,它会报告错误。

我在eclipse上进行了测试,结果是正确的

我的代码怎么了?

为什么要执行String.valueOfroot.val?这是将int变量转换为字符串,并将0添加到1作为字符串,而不是整数,因此结果是错误的。

对于[0,1],您似乎构建了一个树1->0,-而不是0->-,1。因此是10而不是1。所以算法确实起作用了

手术成功,病人死亡

请不要吃沙拉。。。也是