【问题标题】:Invert Binary Tree: how to swap correctly entire left tree and right tree反转二叉树:如何正确交换整个左树和右树
【发布时间】:2021-02-28 02:26:29
【问题描述】:

我很困惑如何在 golang 中正确交换二叉树。 假设我们有低于 BST

Input BST1
     1
    / \
   2   3
  / \  / \
 4  5 6   7
/ \
8  9

...
output BST2
     1
    / \
   3   2
  / \  / \
 7  6 5   4
         / \
        9   8

...
Why not this? BST3
     1
    / \
   3   2
  / \  / \
 5  4 7   6
/ \
9  8

我发现下面的代码会输出正确的答案,我理解交换 2 和 3 是可行的,因为树一开始就站在 1 处。但是,当我们开始递归时,我们将tree 向左移动,例如,现在无法交换左树的4 和右树的7。由于每次我们进行递归(在if tree.Left != nil 内部,我们将节点向左移动,我不确定为什么我们可以交换左侧(如 4)节点和右侧(7)节点。就我目前的理解,BST3`似乎是正确的输出......

type BinaryTree struct {
    Value int

    Left  *BinaryTree
    Right *BinaryTree
}

func (tree *BinaryTree) InvertBinaryTree() {
    
    tree.Left, tree.Right = tree.Right, tree.Left
    if tree.Left != nil{
        tree.left.InvertBinaryTree
    }
    if tree.Right != nil {
        tree.Right.InvertBinaryTree
    } 

【问题讨论】:

    标签: go binary-tree binary-search-tree


    【解决方案1】:

    您正在交换 节点,而不是它们包含的值。因此,所有的孩子都来了。交换根的子节点后,“2”的子节点仍将是 4 和 5(一旦交换该节点的子节点,它们将是 5 和 4)。您正在“重新布线”整个结构,而不是拾取数字并将它们放在同一结构内的新位置。

    【讨论】:

    • 谢谢!正如您所解释的,我认为tree.Left, tree.Right = tree.Right, tree.Left 正在交换值,但实际上是 nodes (有孩子)。我现在明白了一切是如何运作的。
    猜你喜欢
    • 1970-01-01
    • 2012-03-02
    • 2020-08-24
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多