# leetcode系列（11）二叉树翻转 Invert Binary Tree

     4
/   \
2     7
/ \   / \
1   3 6   9
to
     4
/   \
7     2
/ \   / \
9   6 3   1

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

C++代码

/**
* 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 != NULL) {
TreeNode* tmp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tmp);
}
return root;
}
};

Python代码

# 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 root != None:
tmp = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(tmp)
return root

• 本文已收录于以下专栏：

## LeetCode 226 Invert Binary Tree（转换二叉树）

• NoMasp
• 2015-12-27 12:31
• 2504

## LintCode --invert-binary-tree(翻转二叉树)

LintCode --invert-binary-tree(翻转二叉树) 原题链接：http://www.lintcode.com/zh-cn/problem/invert-binary-tre...

## PAT (Advanced Level) Practise 1102. Invert a Binary Tree (25) 二叉树的层序和中序遍历

1102. Invert a Binary Tree (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 1...

## LeetCode | Binary Tree Maximum Path Sum（二叉树的路径最大值）

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tre...

## leetcode 236. Lowest Common Ancestor of a Binary Tree-二叉树共同祖先|深度遍历|递归|非递归

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)