LeetCode Binary Tree PostorderTranversal
2024-08-30 14:11:19
Problem Description
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3}
,1
\
2
/
3return
[3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
Problem Solution
1. 递归方案
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> nodeVec;
public:
void traverse(TreeNode *root){
if(root==NULL)
return;
traverse(root->left);
traverse(root->right);
nodeVec.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root) {
traverse(root);
return nodeVec;
}
};
2. 非递归方案
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> nodeVec;
public:void iterTraverse(TreeNode *root){
if(root==NULL)
return;
stack<TreeNode*> st; TreeNode *pCur,*pPrev=NULL; //pCur: current tree node, pPrev: previous visited tree node
st.push(root);
while(!st.empty())
{
pCur=st.top();
if((pCur->left == NULL && pCur->right == NULL) || (pPrev != NULL && (pCur->left==pPrev || pCur->right==pPrev)))
{
nodeVec.push_back(pCur->val);
pPrev=pCur;
st.pop();
}
else
{
if(pCur->right != NULL)
st.push(pCur->right);
if(pCur->left != NULL)
st.push(pCur->left);
}
}
}
vector<int> postorderTraversal(TreeNode *root) {
iterTraverse(root);
return nodeVec;
}
};
最新文章
- 搭建OpenGL环境-Windows/VS2013
- spring mvc 传参数
- 第二章 rabbitmq在mac上的安装
- linux进程后台运行的几种方法
- fedora下的dropbox
- LNMP1.2一键安装教程
- ubuntn 虚拟机NAT 静态IP 网络配置
- 浅谈C++中指针和引用的区别者之间的区别和用法(转)
- 【算法系列学习】codeforces C. Mike and gcd problem
- SpringCloud的微服务网关:zuul(理论)
- android开发之调试技巧
- 【Django-URL name详解005】
- 六、编写第一个应用【外部nodejs调用】
- 从svn下载项目,并在tomcat启动
- memcached分析
- oracle归档日志的操作
- jar依赖
- Ignite内存数据库与sql支持
- el表达式 多条件判断
- webstorm软件使用记录
热门文章
- PHP实现---汉字简体繁体转换
- LAMP架构的搭建 和wordpress
- java oracle clob string 大字符串存储【转】
- Linux环境下用Weblogic发布项目【二】 -- 配置Domain域
- django error: DisallowedHost: Invalid HTTP_HOST header: &#39;&#39;. You may need to add u&#39;&#39; to ALLOWED_HOST
- UVA10462:Is There A Second Way Left? (判断次小生成树)
- kvm增加硬盘挂载
- JSP动态合并单元格
- 「模板」 FHQ_Treap
- 【bzoj】1927 [Sdoi2010]星际竞速