首页 > 解决方案 > 将二叉树附加到另一个二叉树

问题描述

该方法将树T1和T2的内部结构附加​​为叶子引用p的左右子树,并将T1和T2重置为空树;如果 p 不是叶子,则会发生错误情况。

public void attach(Node p, BinaryTree t1, BinaryTree t2) {
    if (p.left == null) { //logic error??
        p.left = t1.root;
        t1.root = null;
    }
    if (p.right == null) {
        p.right = t2.root;
        t1.root = null;
    }
    else
        System.out.print("is not leaf");
}

标签: javabinary-tree

解决方案


不要删除 t1 和 t2 根,当您将 t1.root 分配给 p.left 并将 t2.root 分配给 p.right 时,任务就完成了。

这是因为 java 使用 t1 和 t2 对象来引用 p.left 和 p.right

public void attach(Node p, BinaryTree t1, BinaryTree t2){
    if(p.left ==null){
        p.left=t1.root;
    }
    if(p.right==null){
        p.right=t2.root;
    }
    else
        System.out.print("is not leaf");
}

推荐阅读