LeetCode----树
来源:互联网 发布:net高级编程 编辑:程序博客网 时间:2024/05/16 12:10
1.题目:Invert Binary Tree
4 / \ 2 7 / \ / \1 3 6 9to
4 / \ 7 2 / \ / \9 6 3 1
思路:
递归的交换左右子树
代码:
* 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(NULL==root) { return NULL; } TreeNode *temp=root->left; root->left=invertTree(root->right); root->right=invertTree(temp); return root; }};
可以改进的地方:使用递归的代价是十分巨大的:它会消耗大量的内存!!递归循环时它用的是堆栈,而堆栈的资源是十分有限的。
递归的本质和栈数据的存取很相似了,都是先进去,但是往往最后处理!再者对于递归函数的局部变量的存储是按照栈的方式去存的,对于每一层的递归函数在栈中都保存了本层函数的局部变量,一边该层递归函数结束时能够保存原来该层的数据!如图:http://www.2cto.com/kf/201303/195338.html
如上图递归式依次往下进行的,并且在该层递归函数还没结束即将进入下一层递归调用时,将会把该层函数中的局部变量保存起来,以供下次使用!
改进的方法:
思路:
1)堆栈
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == NULL) return NULL; stack<TreeNode *> s; s.push(root); while(!s.empty()) { TreeNode *node = s.top(); s.pop(); swap(node->left , node->right); if(node->left) s.push(node->left); if(node->right) s.push(node->right); } return root; } };
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == NULL) return NULL; queue<TreeNode *> s; s.push(root); while(!s.empty()) { TreeNode *node = s.front(); s.pop(); swap(node->left , node->right); if(node->left) s.push(node->left); if(node->right) s.push(node->right); } return root; } }; <strong></strong>
0 0
- LeetCode----树
- leetcode:树
- Leetcode 树 Same Tree
- Leetcode 树 Symmetric Tree
- leetcode:构建二叉树
- Leetcode分类-树
- LeetCode 对称树解法
- Leetcode 平衡树判别
- 重建二叉树 leetcode
- leetcode 124 【树直径】
- leetcode Symmetric Tree 树
- LeetCode -- Flatten 二叉树
- leetcode -- 线段树理解
- leetcode-构造二叉树
- leetcode二叉树遍历
- Leetcode 树的遍历
- leetcode 树遍历变种
- leetcode 重建二叉树
- Mybatis 高级结果映射 ResultMap Association Collection
- ArrayList的contains方法
- PYTHON写爬虫时用到的相对路径-urljoin
- 十年后还会是这样,因为人家60年前已经知道是这样了
- 批量发工资或发邮件
- LeetCode----树
- python学习笔记(三)
- .NET开发需要养成一种良好的注释代码习惯篇
- IP101A芯片默认物理地址(PHY Adress)确定
- IE 11下载文件中文乱码解决(go/php)
- poj Wormholes (最短路 spfa Bellman-Ford 算法 邻接表实现)
- 添加对象到对象仓库的三种方法
- Windows QT环境配置
- 写代码,是一件幸福的事儿