【刷题之路】二叉树的前中后序遍历(非递归)
来源:互联网 发布:360防蹭网软件 编辑:程序博客网 时间:2024/06/01 09:24
经典算法
class TreeToSequence {
public:
vector<vector<int> > convert(TreeNode* root) {
// write code here
vector<vector<int> > res;
res.push_back(fronttree(root));
res.push_back(midtree(root));
res.push_back(backtree(root));
return res;
}
vector<int> fronttree(TreeNode* root){
stack<TreeNode*> temp; //将节点放入栈中操作
vector<int> res;
TreeNode* cur;
temp.push(root);
while(!temp.empty()){
cur=temp.top(); //每次循环弹出栈顶节点,并将此节点先压入右子节点,再压入左子节点,重复循环
temp.pop();
res.push_back(cur->val);
if(cur->right) temp.push(cur->right);
if(cur->left) temp.push(cur->left);
}
return res;
}
vector<int> midtree(TreeNode* root){
vector<int> res;
stack<TreeNode*> temp;
TreeNode* cur;
temp.push(root);
cur=temp.top();
while(!temp.empty()){
if(cur!=NULL && cur->left!=NULL){ //一直遍历直到最后一个左子节点
cur=cur->left;
temp.push(cur);
}
else{
cur=temp.top(); //当前栈顶节点左子结点为空,则弹出栈顶元素,判断该节点的右子节点是否为空
res.push_back(cur->val);
temp.pop(); //简单来说,压入时判断左子节点是否为空,弹出是判断右子节点是否为空
cur=cur->right;
if(cur) temp.push(cur);
}
}
return res;
}
vector<int> backtree(TreeNode* root){
vector<int> res;
stack<TreeNode*> temp1; //两个栈配合操作
stack<TreeNode*> temp2;
TreeNode* cur;
temp1.push(root);
while(!temp1.empty()){
cur=temp1.top(); //1栈顶元素一直压入1栈
temp1.pop();
temp2.push(cur);
if(cur->left) temp1.push(cur->left); //若1栈顶元素有孩子,则按左右顺序押入1栈,重复操作
if(cur->right) temp1.push(cur->right);
}
while(!temp2.empty()){ //将2栈元素弹出,即为后序遍历
res.push_back(temp2.top()->val);
temp2.pop();
}
return res;
}
};
- 【刷题之路】二叉树的前中后序遍历(非递归)
- 二叉树的遍历(递归+非递归+层次遍历)
- 二叉树的遍历(非递归)
- 二叉树的遍历(非递归)
- 二叉树的遍历(非递归)
- 数据结构之二叉树遍历(递归和非递归)
- 二叉树之遍历(递归和非递归解法)
- 二叉树的递归,非递归遍历
- 二叉树的递归+非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的遍历--递归+非递归
- 二叉树的递归、非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的前中后序的递归、非递归遍历
- 递归、非递归实现二叉树的前中后序遍历
- 二叉树的前中后序遍历-递归和非递归实现
- 二叉树的前中后序遍历,递归和非递归方式
- 二叉树的创建与前中后序遍历递归非递归
- 怎样修改C盘里windows\system32\drivers\etc里面的hosts文件并保存
- 合并多个excel文件内容
- 欢迎使用CSDN-markdown编辑器
- java 日期转化
- os.walk( )遍历指定目录下的所有文件
- 【刷题之路】二叉树的前中后序遍历(非递归)
- 基于Libevent的HTTP Server
- Mirantis OpenStack Fuel8.0离线安装(MOS8.0本地源)
- 写一个框架的详细步骤
- CodeForce 626E Simple Skewness (贪心+三分)
- jquery datatables 1.10.9 搜索
- liunx底下db数据库比较 SQLite vs MySQL vs PostgreSQL vs Mongodb
- 关于cookie的一些小测试
- springmvc框架引入JqueryEasyUI失败