简体   繁体   English

二叉树递归 removeLeftmost() 方法如何工作?

[英]How does binary tree recursive removeLeftmost() method work?

The specification of the method claims that the method, starting from the root, will remove the leftmost node and repair the tree structure.该方法的规范声称该方法从根开始,将删除最左边的节点并修复树结构。 It also says that if the leftmost node has no left child to attach a right child (may be null ) to parent of leftmost node as left child (I don't see where this happens in the code).它还说,如果最左边的节点没有左子节点将右子节点(可能为null )附加到最左边节点的父节点作为左子节点(我在代码中看不到这种情况发生的位置)。 Here is the code:这是代码:

public BTNode removeLeftmost()
{
    if (left == null)
        return right;

    left = left.removeLeftmost();
    return this;
}

I just don't see how it is returning back the whole tree with the leftmost node returned.我只是不明白它是如何用最左边的节点返回整棵树的。 Mainly the first part is confusing me where it says to return the right child if left == null .主要是第一部分让我感到困惑,它说如果left == null则返回右孩子。 If I were deep into the tree (due to the recursive call), wouldn't returning right cut off a lot of the tree?如果我深入到树中(由于递归调用),返回时会不会切断很多树?

I'm assuming this is a binary search tree because otherwise you wouldn't need to repair the structure, correct?我假设这是一个二叉搜索树,因为否则你不需要修复结构,对吗?

So what it does is it moves along the tree until there are no more branches to the left, ie with respect only to the left, you have reached a leaf.所以它所做的是沿着树移动直到左边没有更多的分支,即仅相对于左边,你已经到达了一片叶子。

if (left !=null){ left = left.removeLeftmost(); }

At this point, it grafts the branch on the right of the child into that spot on the parent where the left tree was (by left = left.removeLeftmost(); again), and then it will return the branch that was previously in the same spot all the way back to the root of the tree.此时,它将子节点右侧的分支left = left.removeLeftmost();到左侧树所在的父节点上的那个位置left = left.removeLeftmost();再次通过left = left.removeLeftmost(); ),然后它会返回之前在子节点中的分支一直到树根的同一地点。

Here's the case it's handling:这是它处理的情况:

          9
         / \ 
        8   12
       / \
      5   20
       \ 
        6
         \
          7

When we get to 5 , it's the leftmost node ( left == null ).当我们到达5 ,它是最左边的节点( left == null )。 We need to remove it.我们需要删除它。 So the right of 5 (ie 6 ) is returned to the caller ( return right; ), and the caller makes 6 the new left tree of 8 ( left = left.removeLeftmost() )..这样的权5 (即6 )被返回给调用者( return right; ),和呼叫方使6的新的左树8left = left.removeLeftmost() )..

          9
         / \
        8   12
       / \
      6   20
       \ 
        7

Then 8 is returned to the caller ( return this ) and assigned as the left node of 9 ( left = left.removeLeftmost() ).然后8返回给调用者( return this )并分配为9的左节点( left = left.removeLeftmost() )。 But 8 was already the left child of 9 , so this doesn't change anything.但是8已经是9的左孩子,所以这不会改变任何东西。

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

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