周练(2)226. 翻转二叉树
226. 翻转二叉树
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
C++版本:
/*
* @lc app=leetcode.cn id=226 lang=cpp
*
* [226] 翻转二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) {
return root;
}
invertTree(root->left);
invertTree(root->right);
if (root) {
TreeNode *t = root->left;
root->left = root->right;
root->right = t;
}
return root;
}
};
// @lc code=end
python版本:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root == None:
return root
self.invertTree(root.left)
self.invertTree(root.right)
if root:
t = root.left
root.left = root.right
root.right = t
return root