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