描述
操作给定的二叉树,将其变换为源二叉树的镜像。
例如:
- 源二叉树
![](/images/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%95%9C%E5%83%8F-%E7%A4%BA%E4%BE%8B1.png)
- 镜像二叉树
![](/images/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%95%9C%E5%83%8F-%E7%A4%BA%E4%BE%8B2.png)
题解
根据二叉树镜像的定义,考虑递归遍历(dfs)二叉树,交换每个节点的左 / 右子节点,即可生成二叉树的镜像
- 特判:如果pRoot为空,返回空
- 交换左右子树
- 把pRoot的左子树放到Mirror中镜像一下
- 把pRoot的右子树放到Mirror中镜像一下
- 返回根节点root
![](/images/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%95%9C%E5%83%8F.png)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package main
type TreeNode struct { Val int Left *TreeNode Right *TreeNode }
func Mirror( pRoot *TreeNode ) *TreeNode { if pRoot == nil { return nil }
left := Mirror(pRoot.Left) rigth := Mirror(pRoot.Right)
pRoot.Left = rigth pRoot.Right = left
return pRoot }
|