【LeetCode】226. Invert Binary Tree 翻转二叉树(Easy)(JAVA)
题目地址: https://leetcode.com/problems/invert-binary-tree/
题目描述:
Invert a binary tree.
Example:
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.
题目大意
翻转一棵二叉树。
解题方法
- 采用递归,计算 invertTree(root.left) 和 invertTree(root.right)
- 把 root.left 和 root.right 交换
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return root;
TreeNode right = invertTree(root.right);
root.right = invertTree(root.left);
root.left = right;
return root;
}
}
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36 MB,击败了65.11% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)