1086. Tree Traversals Again (25)
2015-11-23 23:21
549 查看
1.如果上次没有弹出,并且栈为空,则这次压入的为根
2.如果上次有弹出,并且这次压入,那么上次弹出的是父节点,这次压入的是右子节点
3如果上次没有弹出,并且这次压入,那么这次压入的是栈头的左子节点
4.每次弹出一个节点,都要把这个节点记录下来,lastPop
AC代码:
2.如果上次有弹出,并且这次压入,那么上次弹出的是父节点,这次压入的是右子节点
3如果上次没有弹出,并且这次压入,那么这次压入的是栈头的左子节点
4.每次弹出一个节点,都要把这个节点记录下来,lastPop
AC代码:
//#include<string> //#include <iomanip> //#include<stack> //#include<unordered_set> //#include <sstream> //#include "func.h" //#include <list> #include<unordered_map> #include<set> #include<queue> #include<map> #include<vector> #include <algorithm> #include<stdio.h> #include<iostream> #include<string> #include<memory.h> #include<limits.h> #include<stack> using namespace std; struct TreeNode { int val; TreeNode*l, *r; TreeNode() :val(-1), l(NULL), r(NULL){}; TreeNode(int x) :val(x), l(NULL), r(NULL){}; }; void InOrder(TreeNode*root, vector<int>&in) { if (root) { InOrder(root->l, in); InOrder(root->r, in); in.push_back(root->val); } } int main(void) { stack<TreeNode*> sta; TreeNode*root = NULL; TreeNode*lastPop = NULL; int n; cin >> n; for (int i = 0; i < 2 * n; i++) { string str; cin >> str; if (str == "Push") { int tmp; cin >> tmp; if (sta.empty() && lastPop == NULL) { root = new TreeNode(tmp); sta.push(root); } else if (lastPop) {//如果上次pop出了,这次压入,证明是右子树 lastPop->r = new TreeNode(tmp); sta.push(lastPop->r); } else { sta.top()->l = new TreeNode(tmp); sta.push(sta.top()->l); } lastPop = NULL;//这次是压入,所以没有上次Pop出的元素的值 } else {//这次是pop出,所以需要存储pop出的元素 TreeNode*head = sta.top(); sta.pop(); lastPop = head; } } vector<int> in(0); InOrder(root, in); for (int i = 0; i < in.size(); i++) { cout << in[i]; if (i != in.size() - 1) cout << " "; } cout << endl; return 0; }
相关文章推荐
- 1086. Tree Traversals Again (25)
- Daily Scrum - 11/23
- VIM AIRLINE 配置问题
- 多线程 同步synchronized、通信wait、notify
- 1014. Waiting in Line (30)
- AIDL简单使用
- glusterfs Connection failed. Please check if gluster daemon is operational. 解决方法
- QUT——XiaoCai (签到未成功)
- 不用main方法,使用静态方法也可以打印Hello World
- Raid及mdadm命令
- hihocoder 1251 Today Is a Rainy Day 2015北京区域赛C
- [leetcode]Factorial Trailing Zeroes
- Lightoj 1021 Painful Bases (状压dp 有趣)
- pymongo异常-OperationFailure: command SON(...)
- hdu 4393 Throw nails(STL之优先队列)
- cheng gong de daima
- AI图片剪切
- map containsKey与get方法区别
- SIGCHLD和waitpid的使用
- svn-bak-daily.bat