关闭

leetcode系列(11)二叉树翻转 Invert Binary Tree

标签: c++pythonleetcode
1381人阅读 评论(0) 收藏 举报
分类:

Invert a binary tree

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

整个题目有意思的是Homebrew作者的google白板编程跪事件,所以这个题目的后面也说了:

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.

用递归可以方便解决,invert根节点的左子树和子树,然后交换两个子树木,就是invert了整个树

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:49144次
    • 积分:1505
    • 等级:
    • 排名:千里之外
    • 原创:105篇
    • 转载:0篇
    • 译文:0篇
    • 评论:5条
    文章分类
    最新评论