LeetCode226.翻转二叉树Golang版
1.问题描述
翻转一棵二叉树。
示例:
输入:
4
/
2 7
/ \ /
1 3 6 9
输出:
4
/
7 2
/ \ /
9 6 3 1
2. 思路
思路,二叉树的遍历
递归前序,后序遍历都可以,中序遍历会导致一些节点左右孩子反转两次
迭代前中后都可以
层序遍历也可以
3. 代码
3.1. 第一种写法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
rightTree := root.Right
root.Right = invertTree(root.Left)
root.Left = invertTree(rightTree)
return root
}
3.2. 前序,后序递归
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 1. 前序遍历
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
invertTree(root.Left)
invertTree(root.Right)
root.Left, root.Right = root.Right, root.Left
return root
}
// 2. 后序遍历
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}
3.3. 层序遍历
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
queue := []*TreeNode{root}
for len(queue) > 0 {
length := len(queue)
for i := 0; i < length; i++ {
if queue[0].Left != nil {
queue = append(queue, queue[0].Left)
}
if queue[0].Right != nil {
queue = append(queue, queue[0].Right)
}
queue[0].Left, queue[0].Right = queue[0].Right, queue[0].Left
queue = queue[1:]
}
}
return root
}
3.3. 前序,后序迭代
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 前序迭代
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
stack := []*TreeNode{}
node := root
for node != nil || len(stack) != 0 {
for node != nil {
node.Left, node.Right = node.Right, node.Left
stack = append(stack, node)
node = node.Left
}
node = stack[len(stack) - 1].Right
stack = stack[0:len(stack)-1]
}
return root
}
// 后序迭代
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
stack := []*TreeNode{}
node := root
for node != nil || len(stack) != 0 {
for node != nil {
node.Left, node.Right = node.Right, node.Left
stack = append(stack, node)
node = node.Right
}
node = stack[len(stack) - 1].Left
stack = stack[0:len(stack)-1]
}
return root
}