给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
226. 翻转二叉树 - 力扣(LeetCode)
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
示例 2:
输入:root = [2,1,3] 输出:[2,3,1]
示例 3:
输入:root = [] 输出:[]
C++代码:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr) return nullptr;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
TreeNode* tmp=left;
root->left=right;
root->right=tmp;
return root;
}
};
TreeNode* tmp=left;
root->left=right;
root->right=tmp;
也可以简洁写成:swap(root->left,root->right);
Python代码:
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return root
left = self.invertTree(root.left)
right = self.invertTree(root.right)
tmp = left
root.left = right
root.right = tmp
return root
# 复杂度分析:
# 时间复杂度:O(N)
# 空间复杂度:O(N)
tmp = left
root.left = right
root.right = tmp
也可以简洁写成:root.left,root.right = right,left