# 你能在白板上写出如何反转一棵二叉树吗？

## 题解

package i

/**
* @author: Jack
* 2020-05-08 13:41
*

4
/   \
2     7
/ \   / \
1   3 6   9

4
/   \
7     2
/ \   / \
9   6 3   1

*/

fun mirrorTree(root: TreeNode?): TreeNode? {
if (null == root) return null

mirrorNode(root)

mirrorTree(root.left)
mirrorTree(root.right)

return root
}

private fun mirrorNode(root: TreeNode) {
val right = root.right
root.right = root.left
root.left = right
}

class TreeNode(var n: Int) {
var left: TreeNode? = null
var right: TreeNode? = null

override fun toString(): String {
return "TreeNode(n=$n, left=$left, right=\$right)"
}
}

fun main() {
val root = TreeNode(4)

val left = TreeNode(2)
root.left = left
left.left = TreeNode(1)
left.right = TreeNode(3)

val right = TreeNode(7)
root.right = right
right.left = TreeNode(6)
right.right = TreeNode(9)

println(root)

mirrorTree(root)

println(root)

}


TreeNode(n=4, left=TreeNode(n=2, left=TreeNode(n=1, left=null, right=null), right=TreeNode(n=3, left=null, right=null)), right=TreeNode(n=7, left=TreeNode(n=6, left=null, right=null), right=TreeNode(n=9, left=null, right=null)))
TreeNode(n=4, left=TreeNode(n=7, left=TreeNode(n=9, left=null, right=null), right=TreeNode(n=6, left=null, right=null)), right=TreeNode(n=2, left=TreeNode(n=3, left=null, right=null), right=TreeNode(n=1, left=null, right=null)))


OK，也许你写出来了反转二叉树的代码，但是你就是写不出来homebrew，这个世界太扯淡了……