欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

leetcode笔记:Invert Binary Tree

程序员文章站 2023-08-26 09:38:34
一. 题目描述 invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4...

一. 题目描述

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

四. 小结

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