[leetcode] 226. Invert Binary Tree
来源:互联网 发布:vb程序设计 贪吃蛇 编辑:程序博客网 时间:2024/05/01 11:22
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9
to
4 / \ 7 2 / \ / \9 6 3 1
Trivia:
This problem was inspired bythis original tweet byMax 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.
这道题是反转二叉树,找出它的镜像,题目难度为easy。
题目本身比较简单,亮点是Trivia的内容。。
可以分别采用深度优先(DFS)和广度优先(BFS)两种策略,所谓深度优先就是采用递归地方法,具体代码:
class Solution {public: TreeNode* invertTree(TreeNode* root) { if(!root) return root; else { swap(root->left, root->right); invertTree(root->left); invertTree(root->right); return root; } }};广度优先即采用层次序遍历二叉树,这里需要借助队列,具体代码:
class Solution {public: TreeNode* invertTree(TreeNode* root) { if(!root) return root; queue<TreeNode*> level; level.push(root); while(!level.empty()) { int sz = level.size(); for(int i=0; i<sz; i++) { TreeNode* curNode = level.front(); level.pop(); swap(curNode->left, curNode->right); if(curNode->left) level.push(curNode->left); if(curNode->right) level.push(curNode->right); } } return root; }};
0 0
- LeetCode 226. Invert Binary Tree
- [leetcode] 226.Invert Binary Tree
- [leetcode] 226. Invert Binary Tree
- 【LeetCode】226. Invert Binary Tree
- leetCode 226. Invert Binary Tree
- LeetCode #226. Invert Binary Tree
- [LeetCode]226. Invert Binary Tree
- 226. Invert Binary Tree LeetCode
- LeetCode 226. Invert Binary Tree
- LeetCode 226. Invert Binary Tree
- leetcode:226. Invert Binary Tree
- LeetCode 226. Invert Binary Tree
- [LeetCode]226. Invert Binary Tree
- leetcode 226. Invert Binary Tree
- 【LeetCode】226. Invert Binary Tree
- #leetcode#226. Invert Binary Tree
- LeetCode *** 226. Invert Binary Tree
- leetcode: 226. Invert Binary Tree
- JAVA过滤器
- VOLUME-FLOW 流程 2015-12-3
- Android 屏幕旋转 处理 AsyncTask 和 ProgressDialog 的最佳方案
- android:windowSoftInputMode的九大属性详解
- linux命令TOP参数load average详解[转]
- [leetcode] 226. Invert Binary Tree
- Android View 事件分发机制 源码解析 (上)
- Linux远程桌面(1)-Linux to Linux(转)
- 采用tmpfs文件系统极速优化ganglia磁盘IO性能20151203
- Linux内核驱动之GPIO子系统(一)GPIO的使用
- C#利用反射遍历对象的属性和属性值
- java中方法为什么需要返回值?
- nginx lua
- jquery基础学习笔记