我是第一次在Binary Search Tree上工作,并试图从Binary Search Tree中删除一个节点。
但是,每次我删除它,然后使用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();
}
如何解决这个问题?
答案 0 :(得分:1)
更改下一行
def patient_slices(ALL_IDS): # Generator
for ID in ALL_IDS:
df_slice = df_master[df_master.ID == ID]
yield df_slice
df_slice = patient_slices(ALL_IDS)
for _ in xrange(len(ALL_IDS)): # Call the generator n times
sinlge_patient = next(df_slice) # Next patient for every call
your_processing(sinlge_patient) # Do your magic
收件人
// Deleting minimum node from right now
deleteNode(root.right, minNodeForRight.data);