一. 题目描述
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
四. 小结
该题意在帮助我们复习数据结构的基础。
时间: 2024-10-08 16:24:08