翻转二叉树
来源:互联网 发布:nginx 会话校验 编辑:程序博客网 时间:2024/05/21 12:28
翻转一棵二叉树
样例
1 1 / \ / \2 3 => 3 2 / \ 4 4
递归版本
先翻转左子树,后翻转右子树,然后对整个树进行翻转
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);}
非递归版本
非递归版本用栈来实现,到访问到头节点的时候,将其左子树和右子树互换即可。
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/)
阅读全文
0 0
- C++二叉树翻转
- 翻转二叉树
- 翻转二叉树
- 题目:翻转二叉树
- LintCode 翻转二叉树
- LinkCode-翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode_175_翻转二叉树
- 二叉树翻转
- lintcode ----翻转二叉树
- lintcode,翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode-翻转二叉树
- 51nod1080
- [博弈 杂题] Codeforces 794E Round #414 E. Choosing Carrot
- struts2多图片上传实例
- T_UPFILE
- 每天一个 Linux 命令(40):wc命令
- 翻转二叉树
- Yarn FairSheduler使用FairSharePolicy计算Fair Share的规则、原理和代码实现
- 黑马--LINUX学习笔记(四)
- (75)蓝图基础脚本
- HTML综合入门
- [线段树] Codeforces 794F Round #414 F. Leha and security system
- 排序算法总结(10)--桶排序
- AngularJS 服务(Service)
- Javascript中Event事件的属性大全