如何在二叉树中添加节点
<前><代码> (5)根 (3)-----^--------(7) (2)---^----(5) ^-----(8)
我想在此二叉搜索树中添加数据为 5 的节点。请帮忙。
(5)Root (3)-------^--------(7) (2)---^----(5) ^-----(8)
I want to add node with data 5 in this binary Search tree. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意:这个答案假设您正在谈论二叉搜索树。
从根开始遍历二叉树:
如果到达一个节点,则可以在其中不要再深入了,因为没有子树,这是插入新元素的地方
<前><代码> (5)根
(3)-----^--------(7)
(2)---^----(5) ^-----(8)
(5)--^
你从
(5),然后向左(因为 5 <= 5)到
(3)
,然后向右(因为 5 > 3)到(5)
,然后你想要转到左子树(因为 5 <= 5),但是您看到没有子树,因此这是插入新元素(5)
的位置。Note: This answer assumes you are talking about a binary search tree.
You traverse the binary tree from the root:
if you arrived at a node, where you can not go any deeper, because there is no subtree, this is the place to insert your new element
You start at
(5)
, then go left (since 5 <= 5) to(3)
, then go right (since 5 > 3) to(5)
, then you want to go to the left subtree (since 5 <= 5), but you see that there is no subtree, so this is the place to insert your new element(5)
.这取决于您是否想要保持二叉树:
如果这两个都不是要求,那么添加元素的最快方法是将其作为新根,并使树的其余部分具有其子元素之一
:二叉搜索树不应该有重复的值,并且插入过程更复杂,需要遍历树来找到插入点。请参阅此处。
对于自平衡二叉搜索树,它甚至更加复杂,例如可能涉及执行树旋转 。请参阅此处了解更多详细信息。
It depends on whether you want to keep your binary tree:
If neither of these are requirements then the fastest way to add an element is to put it as the new root and have the rest of the tree has one of its children:
For binary search trees you should not have repeated values and the process for insertion is more complicated and requires traversing the tree to find the insertion point. See here.
For self-balancing binary search trees it is even more complicated and can for example involve performing tree rotations. See here for more details.