leetcode二叉树遍历
来源:互联网 发布:电子图书数据库有哪些 编辑:程序博客网 时间:2024/06/10 01:05
二叉树的遍历主要以根节点为中心展开思路去写,这里先讲下前序遍历非递归,通常的数组二叉树,
都是以标记进行,这里由于是链式二叉树,所以可以通过把每个节点的左右节点指向变为NULL,这样
第二次遍历到就可以通过左右节点进行判断,从而加入结果遍历中:
后序遍历非递归:
class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int> v; if(root==NULL) return v; stack<TreeNode*> s; s.push(root); while(!s.empty()){ TreeNode *cur=s.top(); if(cur->left==NULL&&cur->right==NULL){ v.push_back(cur->val); s.pop(); } else{ if(cur->right){ s.push(cur->right); cur->right=NULL; } if(cur->left){ s.push(cur->left); cur->left=NULL; } } } return v; }};
后序遍历递归:
非递归主要注意vector传值的时候也要用引用。class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int> v; if(root==NULL) return v; postOrder(root,v); return v; } void postOrder(TreeNode *root,vector<int> &v){ if(root->left) postOrder(root->left,v); if(root->right) postOrder(root->right,v); v.push_back(root->val); }};前序遍历非递归:
class Solution {public: vector<int> preorderTraversal(TreeNode *root) { vector<int> v; if(root==NULL) return v; stack<TreeNode*> s; s.push(root); while(!s.empty()){ TreeNode *cur=s.top(); s.pop(); v.push_back(cur->val); if(cur->right){ s.push(cur->right); } if(cur->left){ s.push(cur->left); } } return v; }};前序遍历递归:
class Solution {public: vector<int> preorderTraversal(TreeNode *root) { vector<int> v; if(root==NULL) return v; preOrder(root,v); return v; } void preOrder(TreeNode *root,vector<int> &v){ v.push_back(root->val); if(root->left) preOrder(root->left,v); if(root->right) preOrder(root->right,v); }};中序遍历递归:
vector<int> inorderTraversal(TreeNode *root) { vector<int> v; if(root==NULL) return v; inOrder(root,v); return v; } void inOrder(TreeNode *root,vector<int> &v){ if(root->left) inOrder(root->left,v); v.push_back(root->val); if(root->right) inOrder(root->right,v); }中序遍历非递归:
和后序非递归类似,记得指针赋值NULL。
class Solution {public: vector<int> inorderTraversal(TreeNode *root) { vector<int> v; if(root==NULL) return v; stack<TreeNode*> s; s.push(root); while(!s.empty()){ TreeNode *cur=s.top(); if(cur->left){ s.push(cur->left); cur->left=NULL; } else{ v.push_back(cur->val); s.pop(); if(cur->right){ s.push(cur->right); } } } return v; }};
0 0
- leetcode二叉树遍历
- [leetcode]二叉树遍历
- Leetcode中二叉树的遍历
- 【Leetcode】二叉树层遍历算法
- leetcode 二叉树遍历非递归实现
- LeetCode—二叉树遍历的情况
- leetcode 二叉树安装层次进行遍历
- LeetCode—二叉树的遍历
- leetcode :二叉树的前中后序遍历
- leetcode中二叉树的遍历
- 【LeetCode题解】二叉树的遍历
- 【LeetCode题解】二叉树的遍历
- 【LeetCode题解】二叉树的遍历
- 【LeetCode题解】二叉树的遍历
- LeetCode二叉树遍历的问题
- LeetCode基础--二叉树--层次遍历
- LeetCode基础--二叉树--前序遍历
- LeetCode基础--二叉树--后序遍历
- mac iphone模拟器 真机 操作
- 使用js制作一般网站首页图片轮播效果
- js控住DOM实现发布微博简单效果
- 关于Sturts1.3从页面获取日期然后录入数据库的问题
- 略解cocos2d-x 延迟动画系统。
- leetcode二叉树遍历
- 将一串字符串转变为驼峰样式(字符串练习)
- POJ 1011 Sticks(dfs+剪枝)
- [PAT] B1015
- js中常用的Tab切换
- 抽象语法树
- 从全局中通过class类名获取标签
- 简单的碰壁反弹效果
- event事件学习小节