[LeetCode] Invert Binary Tree
2015-06-12 17:01
225 查看
After reading the quote below the problem, you will be motivated to solve it immediately :-) Well, indeed it is also relative easy. The process of inverting a binary tree is simply 3 steps:
Swap the
Invert the
Invert the
So we immediately have the following simple recursive solution.
Well, you may also want to challenge yourself to solve it iteratively. The iterative solution is basically a level-order traversal. Push all the nodes of the same level to a queue and then swap their
The code is as follows.
Swap the
leftsubtree and the
rightsubtree;
Invert the
leftsubtree;
Invert the
rightsubtree.
So we immediately have the following simple recursive solution.
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return NULL; swap(root -> left, root -> right); root -> left = invertTree(root -> left); root -> right = invertTree(root -> right); return root; } };
Well, you may also want to challenge yourself to solve it iteratively. The iterative solution is basically a level-order traversal. Push all the nodes of the same level to a queue and then swap their
leftsubtree and
rightsubtree and iterate over their subtrees.
The code is as follows.
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return NULL; queue<TreeNode*> level; level.push(root); while (!level.empty()) { TreeNode* node = level.front(); level.pop(); swap(node -> left, node -> right); if (node -> left) level.push(node -> left); if (node -> right) level.push(node -> right); } return root; } };
相关文章推荐
- oracle bulk collect is table of 批量操作
- 在DOS下强制杀进程的命令
- 杭电2012素数判定(我们试着长大,一路跌跌撞撞)
- python中xrange和range的异同
- 黑马程序员——java基础-IO(二)
- Codeforces548B:Mike and Fun
- 敏捷开发之Scrum扫盲篇
- 如何在Git中撤销一切
- AS的ignore
- WebService使用实例
- 使用Emmet加速Web前端开发
- OC3_字典
- c#base64图片格式
- 分布式助手Zookeeper(二)
- 1035. Password (20)
- Android实用方法—activity多个fragment切换
- SourceInsight注册码
- 1035. Password (20)
- javascript 编程题目
- OC班级类