翻转二叉树(递归与非递归)
2015-08-12 06:47
267 查看
翻转一棵二叉树
样例
(175) Invert Binary Tree
http://www.lintcode.com/zh-cn/problem/invert-binary-tree/)
样例
[code] 1 1 / \ / \ 2 3 => 3 2 / \ 4 4
递归版本
先翻转左子树,后翻转右子树,然后对整个树进行翻转[code]void swapTree(TreeNode *&root){ TreeNode *tmp = root->left; root->left = root->right; root->right = tmp; } void invertBinaryTree(TreeNode *root) { // write your code here if(root == NULL) return; invertBinaryTree(root->left); invertBinaryTree(root->right); swapTree(root); }
非递归版本
非递归版本用栈来实现,到访问到头节点的时候,将其左子树和右子树互换即可。[code]void swapTree(TreeNode *&root){ TreeNode *tmp = root->left; root->left = root->right; root->right = tmp; } void invertBinaryTree(TreeNode *root) { // write your code here if(root == NULL) return; stack<TreeNode*> stk; stk.push(root); while(!stk.empty()) { TreeNode *tmp = stk.top(); stk.pop(); swapTree(tmp); if(tmp->left) stk.push(tmp->left); if(tmp->right) stk.push(tmp->right); } }
(175) Invert Binary Tree
http://www.lintcode.com/zh-cn/problem/invert-binary-tree/)
相关文章推荐
- Linux系统下快速删除某个目录下大量文件
- Android怎样进行布局
- 【LeetCode-面试算法经典-Java实现】【116-Populating Next Right Pointers in Each Node(二叉树链接右指针)】
- Animations
- 【LeetCode-面试算法经典-Java实现】【114-Flatten Binary Tree to Linked List(二叉树转单链表)】
- 【LeetCode-面试算法经典-Java实现】【113-Path Sum II(路径和)】
- 多线程
- CodeForces 429B()
- ds18b20驱动终于写好了
- GitHub上史上最全的Android开源项目分类汇总
- 我用的一些Node.js开发工具、开发包、框架等总结
- leetcode 4 Median of Two Sorted Arrays
- Qt打开外部程序的三种方法(两种阻塞,一种不阻塞)
- [LeetCode.Trick]Rotate Array
- 老哥
- Learning Play! 2.4
- C++ Memory Management C++ 内存管理
- Linux下进程间通信概述
- NET下RabbitMQ实践[实战篇]
- NET下RabbitMQ实践[WCF发布篇]