简体   繁体   English

无法删除二叉树中的节点

[英]Unable to delete a node in Binary tree

I am trying to delete the right most node of a binary tree.我正在尝试删除二叉树最右边的节点。 I am using a function to find the right most node which is returning me the the right most node of Binary tree correctly and then I am assigning in the null value.我正在使用一个函数来找到最右边的节点,它正确地返回二叉树的最右边的节点,然后我分配了空值。 But when I am printing the Binary tree the value of right most node is getting printed.Please help me understand why this is happening.但是当我打印二叉树时,最右边节点的值正在打印。请帮助我理解为什么会发生这种情况。

    void deleteNode(Node root, int Key)
{

    Node rightMost = rightmost(root); // returns the right most node
    rightMost = null

}

If I am deleting the link from parent node to the rightmost child then the node is getting deleted but not when I am making the node itself as null.如果我要删除从父节点到最右边的子节点的链接,则该节点将被删除,但当我将节点本身设置为 null 时不会被删除。 This is confusing because if the node itself is null then it should get deleted.这是令人困惑的,因为如果节点本身为空,那么它应该被删除。

The tricky part is that Java is giving you essentially a pointer to the rightmost node, which you're then setting to null.棘手的部分是 Java 实质上为您提供了一个指向最右侧节点的指针,然后您将其设置为 null。

To explain:解释:

Node rightMost = rightmost(root); // returns the right most node

rightMost is now a variable that just contains a memory address, for example 0x0123456 . rightMost现在是一个只包含内存地址的变量,例如0x0123456 So when you say:所以当你说:

rightMost = null

What's actually happening is it's grabbing the node's rightmost address and copying it into this variable rightMost .实际发生的是它获取节点最右边的地址并将其复制到这个变量rightMost You're then setting this copy to null instead of the actual underlying rightmost node.然后将此副本设置为null而不是实际的底层最右边节点。

Analogy: I may set John Smith in my contacts to have home address 1234 State Street.类比:我可以在我的联系人中设置 John Smith 的家庭地址为 1234 State Street。 However, if I change John Smith's address in my contacts to 2345 Main Street, this doesn't actually cause John to move houses!但是,如果我将联系人中 John Smith 的地址更改为 2345 Main Street,这实际上不会导致 John 搬家! I'm just updating my internal reference of where John's home is.我只是在更新我关于约翰家在哪里的内部参考。 Same thing here.这里也是一样。

Java is definitely tricky because it's pass by value but the value is a reference. Java 肯定很棘手,因为它是按值传递的,但值是一个引用。 I highly recommend reading this and this .我强烈推荐阅读这个这个

To actually do what you're asking, you need to be able to access the underlying property and set it, something like this, where node is the parent of the rightmost node:要实际执行您的要求,您需要能够访问基础属性并对其进行设置,如下所示,其中node是最右边节点的父级:

node.right = null

Or you can have some sort of setter that will set the rightmost node to a specified value.或者您可以使用某种设置器将最右边的节点设置为指定值。 If you don't have any way to set the variable using a setter or direct access to the property, it's read-only from your point of view.如果您无法使用 setter 或直接访问属性来设置变量,那么从您的角度来看,它是只读的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM