zoukankan      html  css  js  c++  java
  • UVA

    /*
    题目链接:
    https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=477


    题意:
    给出二叉树的先序和中序遍历序列,输出后序遍历序列


    查阅了的题解:
    http://blog.csdn.net/mobius_strip/article/details/29639065
    http://blog.csdn.net/YI__JIA/article/details/51223006

    */


    //法一:
    #include <iostream>
    #include <string>
    #include <stack>
    using namespace std;
    
    string pre, mid; // 分别表示先序、中序遍历序列 
    stack<char> ans;
    
    void solve(int l1, int r1, int l2, int r2) // left1, right1, left2, right2,分别表示要遍历的树的先序和中序的起止位置 
    {
    	if (l1 > r1) return; //递归退出条件,退出时,先序和中序遍历都没有元素了,满足 l1 == r1 && l2 == r2,则这时按照后面的递归函数调用的参数,便可推理出退出递归的条件 
    	ans.push(pre[l1]);
    	
    	int root = l2;
    	while (pre[l1] != mid[root]) root++; //在中序中找到根节点 
    	int size = root - l2; //左子树的大小
    	
    	//因为是后序,又是用的栈结构,所以先递归右子树,再递归左子树 
    	solve (l1 + 1 + size, r1, root + 1, r2);
    	solve (l1 + 1, l1 + size, l2, root - 1); 
    }
    int main()
    {
    	while (cin >> pre >> mid)
    	{
    		solve(0, (int)pre.size() - 1, 0, (int)mid.size() - 1);
    		
    		while (!ans.empty())
    		{
    			cout << ans.top();
    			ans.pop();
    		}
    		cout << endl;
    	}
    }

    //法二:
    /*
    后来在网上搜能否优化一下时,突然发现,其实根本不需要栈结构的,只要转变一下递归顺序和输出根的顺序,即:
    
    先遍历左子树,再遍历右子树,再输出根节点的元素,那就可以直接边复原树边输出了!而且,STL有性能瓶颈,所以...这种方法其实比法一更优!
    */
    #include <iostream>
    #include <string>
    using namespace std;
    
    string pre, mid; // 分别表示先序、中序遍历序列 
    
    void solve(int l1, int r1, int l2, int r2) // left1, right1, left2, right2,分别表示要遍历的树的先序和中序的起止位置 
    {
    	if (l1 > r1) return; //递归退出条件,退出时,先序和中序遍历都没有元素了,满足 l1 == r1 && l2 == r2,则这时按照后面的递归函数调用的参数,便可推理出退出递归的条件 
    	
    	int root = l2;
    	while (pre[l1] != mid[root]) root++; //在中序中找到根节点 
    	int size = root - l2; //左子树的大小
    	
    	//先递归左子树,再递归右子树,最后输出根节点元素 
    	solve (l1 + 1, l1 + size, l2, root - 1); 
    	solve (l1 + 1 + size, r1, root + 1, r2);
    	cout << mid[root];
    }
    int main()
    {
    	while (cin >> pre >> mid)
    	{
    		int size = (int)pre.size() - 1;
    		solve(0, size, 0, size);
    		
    		cout << endl;
    	}
    }


  • 相关阅读:
    sqlhelper使用指南
    大三学长带我学习JAVA。作业1. 第1讲.Java.SE入门、JDK的下载与安装、第一个Java程序、Java程序的编译与执行 大三学长带我学习JAVA。作业1.
    pku1201 Intervals
    hdu 1364 king
    pku 3268 Silver Cow Party
    pku 3169 Layout
    hdu 2680 Choose the best route
    hdu 2983
    pku 1716 Integer Intervals
    pku 2387 Til the Cows Come Home
  • 原文地址:https://www.cnblogs.com/mofushaohua/p/7789353.html
Copyright © 2011-2022 走看看