LeetCode 剑指 Offer 27. 二叉树的镜像
题目描述
思路分析
思路描述
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
func flipTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
// 交换左右子树
root.Left, root.Right = root.Right, root.Left
// 递归处理左右子树
flipTree(root.Left)
flipTree(root.Right)
return root
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func flipTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
stack := []*TreeNode{root}
for len(stack) > 0 {
cur := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// 交换左右子树
cur.Left, cur.Right = cur.Right, cur.Left
if cur.Left != nil {
stack = append(stack, cur.Left)
}
if cur.Right != nil {
stack = append(stack, cur.Right)
}
}
return root
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用