LeetCode: Binary Tree Postorder Traversal [145]
2024-08-30 07:44:46
【题目】
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
【题意】
非递归实现兴许遍历
【思路】
维护两个栈,一个栈用来存储标记,标记对应的结点的右子树是否已经被遍历。还有一个栈存储树节点,用以模拟后序遍历。
【代码】
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int>result;
TreeNode*node=root;
stack<TreeNode*>st;
stack<bool>st_flag; while(node){
st.push(node);
st_flag.push(false);
node=node->left;
}
while(!st.empty()){
bool status = st_flag.top();
if(!status){
//訪问右子树
st_flag.pop(); st_flag.push(true);
node = st.top();
node=node->right;
while(node){
st.push(node);
st_flag.push(false);
node=node->left;
}
}
else{
//訪问当前结点
st_flag.pop();
node = st.top(); st.pop();
result.push_back(node->val);
}
}
return result;
}
};
最新文章
- controller_name classify constantize model_name
- Windows 删除 .svn标志
- jira插件带ui界面和几种方式
- 一款基于jQuery轮播切换焦点图,可播放多张图片
- ubuntu1304下安装boa服务器
- PAT-乙级-1035. 插入与归并(25)
- 2016年11月2日——jQuery源码学习笔记
- php把文件上传到远程服务器上例子
- java 读取并且显示 txt 文件
- qcow2、raw、vmdk等镜像格式
- PHP提取字符串中的所有汉字
- java中变量赋值的理解
- 找到一个牛的一逼的,超简易ssm和ssh的学习网址
- 【Python语言】Python介绍
- babel-polyfill使用与性能优化
- limits.conf文件工作原理
- Bootstrap datepicker 在弹出窗体modal中不工作
- bootstrap collapse 无法收回
- IAM页面是在统一区分配的还是在混合区分配的?
- 【转】安全加密(一):这些MCU加密方法你都知道吗?