leetcode笔记:Invert Binary Tree
2016-04-07 16:51
381 查看
一. 题目描述
Invert a binary tree.
to
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?),但你居然不会在白板上翻转一棵二叉树,真是操蛋。
这是一道任何程序员都应该会的题,递归或者队列迭代解法都可以实现,不多加赘述。
三. 示例代码
四. 小结
该题意在帮助我们复习数据结构的基础。
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
四. 小结
该题意在帮助我们复习数据结构的基础。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- AVL树-自平衡二叉查找树(Java实现)
- c++ primer 第五版 笔记前言
- 命令行快速技巧:如何定位一个文件
- share_ptr的几个注意点
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- C#算法之关于大牛生小牛的问题
- C++联合体转换成C#结构的实现方法