zoukankan      html  css  js  c++  java
  • 03-树3 Tree Traversals Again(25 分)

    题目

    链接

    分析

    push是二叉树前序遍历的结果,pop是二叉树中序遍历的结果,所以这个题就是已知前序遍历和中序遍历,求后序遍历。

    AC代码

    #include "bits/stdc++.h"
    using namespace std;
    struct TreeNode
    {
    	int left=-1, right=-1;
    }tree[45];
    vector<int> v;
    void postorder(int x) {
    	if (x == -1) return;
    	postorder(tree[x].left);
    	postorder(tree[x].right);
    	//cout << x << ' ';
    	v.push_back(x);
    }
    
    int main() {
    	int n, i, x, t;
    	cin >> n;
    	string str;
    	stack<int> s;
    	t = 0;
    	bool p = true;
    	for (i = 1; i <= 2*n; i++) {
    		cin >> str;
    		if (str == "Push") {
    			cin >> x;
    			s.push(x);
    			if (p)
    				tree[t].left = x;
    			else
    				tree[t].right = x;
    			t = x;
    			p = true;
    		}
    		else if (str == "Pop") {
    			t = s.top();
    			p = false;
    			s.pop();
    
    		}
    		else {
    			cout << "出错了!";
    			return 0;
    		}
    	}
    	//后序遍历二叉树
    	postorder(0);
    	
    	//输出结果
    	for (i = 0; i < v.size() - 1; i++) {
    		cout << v[i];
    		if (i < v.size() - 2)
    			cout << ' ';
    
    	}
    
    	return 0;
    }
    
    
    转载请保留原文链接及作者
    本文标题:
    文章作者: LepeCoder
    发布时间:
    原始链接:
  • 相关阅读:
    Python之实现一个优先级队列
    java可变参数列表的实现
    static 关键字详解 static方法调用非static属性和方法
    this关键字详解
    vue自定义事件 子组件把数据传出去
    vue组件 Prop传递数据
    Vue 什么是组件
    vue v-model 表单控件绑定
    vue v-on监听事件
    vue v-if with v-for
  • 原文地址:https://www.cnblogs.com/lepeCoder/p/7676399.html
Copyright © 2011-2022 走看看