Invert Binary Tree
Invert Binary Tree
题目
invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
思路
递归
解题
c++版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/**
* 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)
return NULL;
TreeNode *tmp=root->left;
root->left=root->right;
root->right=tmp;
root->left=invertTree(root->left);
root->right=invertTree(root->right);
return root;
}
};
Python版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if not root:
return None
tmp=root.left
root.left=root.right
root.right=tmp
root.left=self.invertTree(root.left)
root.right=self.invertTree(root.right)
return root