码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode笔记:Invert Binary Tree

时间:2016-04-08 15:18:37      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

一. 题目描述

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9

to

     4
   /     7     2
 / \   / 9   6 3   1

Trivia:

This problem was inspired by this original tweet by Max Howell:

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.

二. 题目分析

题目意图很明显,即翻转一棵二叉树。后面是几句话,大概的意思是:

Google:我们有90%的工程师在使用你写的软件(Homebrew?),但你居然不会在白板上翻转一棵二叉树,真是操蛋。

这是一道任何程序员都应该会的题,递归或者队列迭代解法都可以实现,不多加赘述。

三. 示例代码

// 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) return root;
        TreeNode* temp = root->left;
        root->left = root->right;
        root->right = temp;

        invertTree(root->left);
        invertTree(root->right);

        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(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return None
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

四. 小结

该题意在帮助我们复习数据结构的基础。

leetcode笔记:Invert Binary Tree

标签:

原文地址:http://blog.csdn.net/liyuefeilong/article/details/51087179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!