【发布时间】: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