2021-12-12:翻转二叉树。力扣226。
答案2021-12-12:
自然智慧。递归。
代码用golang编写。代码如下:
package main
import "fmt"
func main() {
root := &TreeNode{val: 1}
root.left = &TreeNode{val: 2}
root.right = &TreeNode{val: 3}
ret := invertTree(root)
fmt.Println(ret.val)
fmt.Println(ret.left.val)
fmt.Println(ret.right.val)
}
type TreeNode struct {
val int
left *TreeNode
right *TreeNode
}
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
left := root.left
root.left = invertTree(root.right)
root.right = invertTree(left)
return root
}
执行结果如下: