简体   繁体   English

删除二叉搜索树中的节点

[英]Deleting a node in Binary Search Tree

I made a function to delete a node from BST.我做了一个 function 从 BST 中删除一个节点。 I was wondering if the two recursive codes do the same thing or not我想知道这两个递归代码是否做同样的事情

BstNode* temp = new BstNode();
temp = root;
delete(root);
return temp->left;
return root->left;

I know that the first one deletes root from the heap memory but it adds temp to the memory so is it same as the second code?我知道第一个从堆 memory 中删除了根目录,但它向 memory 添加了临时代码,所以它与第二个代码相同吗?

Sorry, but it has to be said clear: This code makes no sense whatsoever.对不起,但必须说清楚:这段代码毫无意义。

 BstNode* temp = new BstNode(); // (1) temp = root; // (2) delete(root); // (3) return temp->left; // (4)

(1) dynamically allocates a BstNode . (1)动态分配一个BstNode After assigning root to temp in (2) the memory allocated in (1) is leaked.(2)中将root分配给temp后,在(1)中分配的 memory 被泄露。 You lost any reference to it.你失去了对它的任何引用。

Then (3) deletes root but temp points to the same, it has the same value as root because of the assignment in (2) .然后(3)删除roottemp指向相同,由于(2)中的分配,它与root具有相同的值。 Hence (4) is undefined behavior due to dereferencing a dangling pointer.因此(4)是由于取消引用悬空指针而导致的未定义行为。

This code is no good.这段代码不好。

On the other hand this:另一方面是:

return root->left;

dereferences root and returns its left member.取消引用root并返回其left成员。 If root is a valid pointer this code is not causing same desaster as the first.如果root是有效指针,则此代码不会导致与第一个相同的灾难。

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

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