Problem Description

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?

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;
}
};

最新文章

  1. 搭建OpenGL环境-Windows/VS2013
  2. spring mvc 传参数
  3. 第二章 rabbitmq在mac上的安装
  4. linux进程后台运行的几种方法
  5. fedora下的dropbox
  6. LNMP1.2一键安装教程
  7. ubuntn 虚拟机NAT 静态IP 网络配置
  8. 浅谈C++中指针和引用的区别者之间的区别和用法(转)
  9. 【算法系列学习】codeforces C. Mike and gcd problem
  10. SpringCloud的微服务网关:zuul(理论)
  11. android开发之调试技巧
  12. 【Django-URL name详解005】
  13. 六、编写第一个应用【外部nodejs调用】
  14. 从svn下载项目,并在tomcat启动
  15. memcached分析
  16. oracle归档日志的操作
  17. jar依赖
  18. Ignite内存数据库与sql支持
  19. el表达式 多条件判断
  20. webstorm软件使用记录

热门文章

  1. PHP实现---汉字简体繁体转换
  2. LAMP架构的搭建 和wordpress
  3. java oracle clob string 大字符串存储【转】
  4. Linux环境下用Weblogic发布项目【二】 -- 配置Domain域
  5. django error: DisallowedHost: Invalid HTTP_HOST header: &#39;&#39;. You may need to add u&#39;&#39; to ALLOWED_HOST
  6. UVA10462:Is There A Second Way Left? (判断次小生成树)
  7. kvm增加硬盘挂载
  8. JSP动态合并单元格
  9. 「模板」 FHQ_Treap
  10. 【bzoj】1927 [Sdoi2010]星际竞速