gpt4 book ai didi

java - 从二叉搜索树中删除节点

转载 作者:行者123 更新时间:2023-12-02 10:37:02 25 4
gpt4 key购买 nike

我第一次使用二叉搜索树,并尝试从二叉搜索树中删除一个节点。

但是,每次我删除它,然后使用 inOrder()preOrder() 来检查它是否被删除时,它仍然会显示,这意味着我无法删除该特定节点。

这是我的代码:

public class BinaryTree<T extends Comparable<T>> {
TreeNode<T> root;
ArrayList<Integer> myArr = new ArrayList<Integer>();
Random random;
}

public void add(T o) {
if (root == null) {
root = new TreeNode<T>(o);
} else {
root.insert(o);
}
}

public TreeNode<T> deleteNode(TreeNode<T> root, int value) {
if (root == null)
return null;
if (root.data > value) {
root.left = deleteNode(root.left, value);
} else if (root.data < value) {
root.right = deleteNode(root.right, value);
} else {
// if nodeToBeDeleted have both children
if (root.left != null && root.right != null) {
TreeNode<T> temp = root;
// Finding minimum element from right
TreeNode<T> minNodeForRight = minimumElement(temp.right);
// Replacing current node with minimum node from right subtree
root.data = minNodeForRight.data;
// Deleting minimum node from right now
deleteNode(root.right, minNodeForRight.data);
}
// if nodeToBeDeleted has only left child
else if (root.left != null) {
root = root.left;
}
// if nodeToBeDeleted has only right child
else if (root.right != null) {
root = root.right;
}
// if nodeToBeDeleted do not have child (Leaf node)
else
root = null;
}
return root;
}

public TreeNode<T> minimumElement(TreeNode<T> root) {
if (root.left == null){
return root;
} else {
return minimumElement(root.left);
}
}

public static void main(String[] args){
BinaryTree<Integer> bst = new BinaryTree<Integer>();
bst.add(20);
bst.add(30);
bst.add(40);
bst.add(80);
bst.add(1200);
bst.inOrder();
bst.deleteNode(bst.root, 80);
bst.inOrder();
}

如何解决这个问题?

最佳答案

更改以下行

// Deleting minimum node from right now
deleteNode(root.right, minNodeForRight.data);

// Deleting minimum node from right now
root.right = deleteNode(root.right, minNodeForRight.data);

关于java - 从二叉搜索树中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53202171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com