简体   繁体   English

二叉树删除

[英]Binary tree deletion

I have a binary tree, and pre-order traversal. 我有一个二叉树,并进行了遍历。 Here is my tree. 这是我的树。

      15
     / \
   10   23
   /\   /\
  5 12 20 30
    /     /
   11    25
          \
          27  

so result of pre-order : 15 10 5 12 11 23 20 30 25 27. It's OK 所以预订的结果是:15 10 5 12 11 23 20 30 2527。可以

Than I delete 5,12 and 23 elements 比我删除5,12和23个元素

Should I get this 我应该得到这个吗

          15
         / \
       10   27
        \   /\
        11 20 30
               \
               25

Result:15 10 11 27 20 30 25 结果:15 10 11 27 20 30 25

or this? 或这个?

      15
     / \
   10   25
    \   /\
    11 20 30
          /
         27 

Result: 15 10 11 25 20 30 27 结果:15 10 11 25 20 30 27

PS I get 2nd case. PS我得到第二种情况。 If it isn't right, what is wrong with deletion? 如果不正确,删除有什么问题?

UPD: SO the second updated variant is right? UPD:那么第二个更新的变体对吗?

Your 2nd case is almost right. 您的第二种情况几乎是正确的。 27 would be a left node of 30. When deleting a top node of a (sub)tree, you can either replace that node with the right-most node of the left branch or the left-most node of the right branch. 27将是30的左节点。删除(子)树的顶部节点时,可以用左分支的最右节点或右分支的最左节点替换该节点。 In this case, you've replaced 30 with the left-most value of the right branch, which is 25. You'd have to perform this recursively as 25 has branches of its own. 在这种情况下,您用右分支的最左边的值25代替了30。您必须递归执行此操作,因为25拥有自己的分支。 Once your target node to delete becomes a leaf, delete it. 一旦您要删除的目标节点成为叶子,就将其删除。

First step: 第一步:

      15
     / \
   10   25
    \   /\
    11 20 30
          /
         23
          \
           27

Second step: 第二步:

      15
     / \
   10   25
    \   /\
    11 20 30
          /
         27
        / 
       23    

Third (deletion): 第三(删除):

      15
     / \
   10   25
    \   /\
    11 20 30
          /
         27

If you want pre-order traversal of the remaining elements to be consistent with the pre-order traversal before the deletes, then your tree should look like this: 如果您希望其余元素的预遍历与删除之前的预遍历一致,则您的树应如下所示:

   15
  / \
10   20
 \    \
 11    30
       /
      25
       \
        27

The delete method is: 删除方法是:

If there's a left subtree of a deleted node, move the root of the left subtree to the deleted position. 如果存在已删除节点的左子树,请将左子树的根移到删除位置。 Follow the right subtree links in the (formerly) left subtree and attach the right subtree to the first empty right link. 遵循(以前)左子树中的右子树链接,并将右子树附加到第一个空的右链接。 If there is no left subtree, move the root of the right subtree to the deleted position. 如果没有左子树,请将右子树的根移到删除位置。

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

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