• A1119 Pre- and Post-order Traversals [前序后序转中序]


    在这里插入图片描述
    前序和后序之所以不确定一棵树的原因就是当只有一棵子树的时候,不确定是左子树还是右子树。找前序的第二个结点在后续中位置,左边就是左子树。递归建树
    要是到最后一个位置还没找出根节点,那么区分不了左右,标志位标记false

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    using namespace std;
    const int maxn = 50;
    struct node
    {
    	int data;
    	node* lchild;
    	node* rchild;
    };
    int pre[maxn], post[maxn];
    int n;
    bool isUnique = true;
    node* create(int prel, int prer, int postl, int postr)
    {
    	if (prel > prer)
    		return NULL;
    	node* root = new node;
    	root->data = pre[prel];
    	int i, numLeft = 0;
    	for (i = postl;i <postr; i++)
    	{
    		numLeft++;
    		if (post[i] == pre[prel + 1])
    			break;
    	}
    	if (i == postr - 1)  
    		isUnique = false;
    	root->lchild = create(prel + 1, prel + numLeft, postl,i);
    	root->rchild = create(prel + numLeft+1, prer, i + 1, postr - 1);
    	return root;
    }
    int flag = 1;
    void inorder(node* root)
    {
    
    	if (root == NULL)
    		return;
    	inorder(root->lchild);
    	if (flag)
    	{
    		cout << root->data;
    		flag = 0;
    	}
    	else
    		cout << " " << root->data;
    	inorder(root->rchild);
    }
    int main()
    {
    	cin >> n;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> pre[i];
    	}
    	for (int i = 0; i < n; i++)
    	{
    		cin >> post[i];
    	}
    	node* root = create(0, n - 1, 0, n - 1);	
    	if (isUnique)
    	{
    		cout << "Yes" << endl;
    		inorder(root);
    		cout << endl;
    	}
    	else
    	{
    		cout << "No" << endl;
    		inorder(root);
    		cout << endl;
    	}
    
    }
    
  • 相关阅读:
    黑马程序员简易聊天器笔记
    黑马程序员 最简单的浏览器
    Java 窗体布局
    黑马程序员交通系统
    黑马程序员–java 网络处理
    Swing入门级项目全程实录学习总结
    Swing入门级项目全程实录第7讲
    Swing入门级项目全程实录第3讲
    Swing入门级项目全程实录第2讲
    HTML基础教程
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812015.html
Copyright © 2020-2023  润新知