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].

思路:后序遍历是按照“左子树,右子树,根”的顺序访问元素。那么根或者其它父亲元素就要先压入栈,然后再弹出。

#include <iostream>
#include <algorithm>
#include <vector>
#include <stack> using namespace std; 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> res;
stack<TreeNode *> s;
if (!root) {
return res;
}
s.push(root);
while (!s.empty()) {
TreeNode *p = s.top(); s.pop();
res.push_back(p->val); if (p->right) {
s.push(p->right);
} if (p->left) {
s.push(p->left);
}
}
reverse(res.begin(), res.end());
return res;
}
}; int main(int argc, char *argv[]) {
TreeNode *p = new TreeNode();
p->right = new TreeNode();
p->left = new TreeNode(); Solution *solution = new Solution(); vector<int> res;
res = solution->postorderTraversal(p); vector<int>::iterator it;
for (it = res.begin(); it != res.end(); it++) {
cout << *it << endl;
} }

最新文章

  1. linux奇技淫巧 4
  2. (五)AOS编程
  3. Windows 下java环境变量的配置(Windows7 ,8,8.1,10)
  4. 超酷的测速网站Ookla SPEEDTEST
  5. 设计模式 策略-Strategy,装饰-Decorator,观察者-Observer
  6. 关于SQL IO的一些资料
  7. 安卓webview下使用zepto的swipe失效
  8. HTML5 页面制作工具
  9. Docker创建MySQL集装箱
  10. html 页面太长滚动时,固定页面菜单标签,或者导航标签的位置,fixed/stickUp the position
  11. DOM操作-引用同级的元素
  12. 【Zookeeper】源码分析之网络通信(一)
  13. Day9 基于TCP的套接字和基于UDP的套接字
  14. 编译内核时出现drivers/mfd/mxc-hdmi-core.c:36:24: fatal error: mach/clock.h: No such file or directory
  15. design mode(php)
  16. HTML命名规范
  17. HeadFirst Ruby 第十五章总结 Saving and loading data
  18. 第04章:MongoDB基本概念
  19. 【Spring Boot&amp;&amp;Spring Cloud系列】Spring Boot中使用数据库之MySql
  20. airtest IDE问题汇总

热门文章

  1. spirng中的asm与jdk不兼容&lt;已解决&gt;
  2. linq 动态判断
  3. oracle:the password has expired
  4. 安装php_sqlsrv扩展
  5. wmi uuid
  6. Ubuntu 双网卡设置
  7. robot framework 中should be true 与should contain 的区别
  8. 跟我学Spring Boot(三)Spring Boot 的web开发
  9. qr 生成二维码
  10. php emoji mysql保存和搜索