二叉树的三种非递归遍历
来源:互联网 发布:ubuntu教程 编辑:程序博客网 时间:2024/06/11 21:21
树的结构
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};
非递归先序遍历:
vector<int> PreorderTraversal(TreeNode* root) { vector<int> re; stack<TreeNode*> s; if(root==NULL) return re; TreeNode* cur=root; while(!s.empty()||cur!=NULL){ while(cur!=NULL){ s.push(cur); re.push_back(cur->val);//第一次遇到就放入 cur=cur->left; } TreeNode* node=s.top(); s.pop(); cur=node->right; } return re; }
非递归后序遍历:
vector<int> PostorderTraversal(TreeNode* root) { vector<int> re; stack<TreeNode*> s; if(root==NULL) return re; TreeNode* cur=root;//用于遍历树的指针 TreeNode* pre=NULL;//记录前面序号的节点 while(!s.empty()||cur!=NULL){ while(cur!=NULL){ s.push(cur);//第一次遇到不访问 cur=cur->left; } TreeNode* node=s.top(); if(node->right==NULL){//没有右节点,当作第三次访问 s.pop(); re.push_back(node->val); pre=node; cur=NULL; }else{ //如果是第二次访问 if(pre==NULL||node->right!=pre){ cur=node->right; }else{//如果第三次访问 s.pop(); re.push_back(node->val); pre=node; cur=NULL; } } } return re; }非递归中序遍历:
vector<int> InorderTraversal(TreeNode* root) { vector<int> re; stack<TreeNode*> s; if(root==NULL) return re; TreeNode* cur=root;//用于遍历树的指针 TreeNode* pre=NULL;//记录前面序号的节点 while(!s.empty()||cur!=NULL){ while(cur!=NULL){ s.push(cur);//第一次遇到不访问 cur=cur->left; } TreeNode *node=s.top(); s.pop();//第二次遇到就应该访问 re.push_back(node->val); cur=node->right; } return re; }
0 0
- 二叉树的三种非递归遍历方式。
- 二叉树的三种非递归遍历
- 二叉树的三种非递归遍历
- 二叉树的三种非递归遍历算法
- 二叉树的三种非递归遍历
- 二叉树的三种非递归遍历
- 二叉树的三种非递归遍历
- 二叉树的三种非递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- 二叉树的递归遍历
- Java中Object类的公有方法
- 自定义View起步:Canvas之绘制图片
- 全月平均法业务存货核算系统应如何操作
- 量化进阶——为什么量化投资一定要多模型
- 常见动态规划问题总结
- 二叉树的三种非递归遍历
- openstack虚拟机无法启动的一次排错经历
- [LeetCode]Two Sum
- 矩阵快速幂
- Android如何区分debug和release两种状态
- HUD 5323 Solve this interesting problem dfs剪枝搜索,重构线段树
- 【Java学习0331】多线程
- 结构体与内存对齐
- 顺序表中删除元素值为x的操作