繁体   English   中英

在Java中删除二进制搜索树的方法实现?

[英]remove method implementation for binary search tree in Java?

BSTremove方法的一种实现。 我从那里引用:

 Removing an element from a search tree, although tricky, 
 is conceptually straight-forward with one (common) exception: removing the element at a 
  node with two non-null children. In this case, the solution is either:

 removeMax: remove the maximum (rightmost) node from the left subtree 
 and replace the root's value with the value of the removed node.
 removeMin: remove the minimum (leftmost) node from the right subtree 
 and replace the root's value with the value of the removed node.

    In either case the search tree's order structure is preserved. 

如果看这个二叉树, 在此处输入图片说明

我想删除8和,如果我选择从挑元件leftTree ,使用removeMax ,我会选择7根据上述的定义。

但是我需要使用removeMinright Tree选择13 ,这会破坏BST

我不是正确理解了吗?

remove工作的方法是从rightTree获取maximum ,或者从rightTree minimum ,然后用其data替换要删除的node

尽管具有外观,但上方右子树的最左侧节点是10,而不是13。到达13时需要向右移动(从10到14),因此13不能是最左侧的节点。 如果选择十,则BST属性将不会损坏。

右侧子树具有三个节点-10、14和13。

   10
     \
      \
       14
      /
     13

十个(在顶部)没有左子树,因此它是右子树的最左节点。

如果10的leftnode不是null而是某个节点怎么办?

然后,树将如下所示:

   10
  /  \
 /    \
9      14
      /
     13

因此最左边的节点将是9,而不是10。 然后,您描述的算法将选择九个要删除的算法,这将再次保留BST属性。

右侧子树的最小值是10,而不是13。

如果需要视觉助记符,可能会有所帮助:右子树的最小值是“右子级的最左后代”。

暂无
暂无

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

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