文章目录
  1. 1. Invert Binary Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

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

文章目录
  1. 1. Invert Binary Tree
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题