首页 > 解决方案 > 建设树

问题描述

我写了一个树的构造方法。运行它时我没有看到任何错误。但是,当我测试树是否对称并且应该返回 false 时(对于输入:[1,2,2,4,4, null, 6])这意味着我将根节点设置为 1,第二级:2,2 第三级:4、4、null、6。它返回true。我不确定有什么问题?我确定我的对称函数是正确的,我只是不知道我的树结构有什么问题?我尝试调试,我看到数组中的所有值都在构造中实现。有人可以让我知道发生了什么吗?

public class isSymmetric {
    public static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int key) {
            this.key = key;
            this.left = this.right = null;
        }
    }
    public boolean symmetric(TreeNode root) {
        ...
    }

    //Tree test cases
    public static TreeNode construction(Integer[] array) {
        //use level order traversal to construct a tree
        TreeNode root = new TreeNode(array[0]);
        return constructionhelp(array, root, 0);

    }
    public static TreeNode constructionhelp(Integer[] array, TreeNode root, int i) {
        if (root == null) {
            return null;
        }
        if (i < array.length) {
            root = new TreeNode(array[i]);
            root.left = constructionhelp(array, root.left, 2*i+1);
            root.right = constructionhelp(array, root.right, 2*i+2);
        }
        return root;
    }

    public static void main(String[] args) {
        isSymmetric s = new isSymmetric();
        Integer a[] = {1,2,2,4,4,null,6};
        TreeNode roota = construction(a);
        System.out.print(s.symmetric(roota));

        }
    }
   //returning true;

标签: javatree

解决方案


怎么了:

root = new TreeNode(array[i]); // you create new tree node instance
root.left = constructionhelp(array, root.left, 2*i+1); // root.left is null
root.right = constructionhelp(array, root.right, 2*i+2) // root.right is null

所以在你constructionhelp再次调用你之后,你null作为节点的参数传递。

->null返回。

-> 你的树只是根。


推荐阅读