[LeetCode] 226. Invert Binary Tree(反转二叉树)
-
Difficulty: Easy
-
Related Topics: Tree
Description
Invert a binary tree.
反转一棵二叉树
Examples
Example 1
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so f*** off.
Solution
“不能在白板上反转一棵二叉树的都是 **?”那今天的题目就不开 IDE 做了,直接裸写代码,相关的解释都在注释里了,自己看吧。
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun invertTree(root: TreeNode?): TreeNode? {
if (root == null) {
return root
}
// 节点的左右子树交换
val t = root.left
root.left = root.right
root.right = t
// 对左右子树进行递归交换
root.left = invertTree(root.left)
root.right = invertTree(root.right)
return root
}
}