您的位置:首页 > 大数据 > 人工智能

1086. Tree Traversals Again (25)

2015-11-23 23:21 549 查看
1.如果上次没有弹出,并且栈为空,则这次压入的为根

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: