226. Invert Binary Tree
2016-03-09 16:51
211 查看
nvert 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.
Subscribe to see which companies asked this question
C++递归代码:
C++非递归代码,主要是BFS宽度优先搜索的思想,利用队列来实现:
C#版本,顺便改了下递归顺序,另外C#版本的代码也可以在JAVA环境中运行,主要是NULL大小写的区别,C#和java是没有定义大写的NULL的。
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.
Subscribe to see which companies asked this question
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 NULL; TreeNode *treeleft=invertTree(root->right); TreeNode *treeright=invertTree(root->left); root->left=treeleft; root->right=treeright; return root; } };
C++非递归代码,主要是BFS宽度优先搜索的思想,利用队列来实现:
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root==NULL) return NULL; queue<TreeNode*>tree_que; tree_que.push(root); while(tree_que.size()>0) { TreeNode *first=tree_que.front(); tree_que.pop(); TreeNode *tmp=first->left; first->left=first->right; first->right=tmp; if(first->left) tree_que.push(first->left); if(first->right) tree_que.push(first->right); } return root; } };
C#版本,顺便改了下递归顺序,另外C#版本的代码也可以在JAVA环境中运行,主要是NULL大小写的区别,C#和java是没有定义大写的NULL的。
public class Solution { public TreeNode InvertTree(TreeNode root) { if(root==null)return null; TreeNode tmp=root.left; root.left=root.right; root.right=tmp; InvertTree(root.left); InvertTree(root.right); return root; } }
相关文章推荐
- 154. Find Minimum in Rotated Sorted Array II
- QT模拟时钟
- 全排列
- MySQL主从复制(Master-Slave)与读写分离(MySQL-Proxy)实践
- 人脸识别,人脸关键点检测算法
- 一个杯子的测试用例
- alibaba/druid 使用ConfigFilter
- linux-mysql-rpm安装方式
- Swift学习之UILabel基本用法
- mysql超一亿条记录中快速查询总记录条数
- 2 million pixels RTMP protocol IP camera,Push stream to FMS/RED5/WOWZA
- UIResponder
- java怎么调用webservice
- 方法兼容
- 升级yosemite后java出错的解决
- boa,cgi 应用过程经验总结(404,502错误解决)
- 【python】编程语言入门经典100例--35
- Tomcat 7 + Java 8 : Invalid byte tag in constant pool: 15
- 【python】编程语言入门经典100例--34
- java集合源码分析