• PAT甲级1127. ZigZagging on a Tree


    PAT甲级1127. ZigZagging on a Tree

    题意:

    假设二叉树中的所有键都是不同的正整数。一个唯一的二叉树可以通过给定的一对后序和顺序遍历序列来确定。这是一个简单的标准程序,可以按顺序打印数字。但是,如果您认为问题太简单,那么您太天真了。
    这次你应该以“锯齿形顺序”打印数字 - 也就是说,从根开始,逐级打印数字,从左到右交替,从右到左。例如,对于以下树,您必须输出:1 11 5 8 17 12 20 15。
    输入规格:

    每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数N(<= 30),即二叉树中的总节点数。第二行给出了无序序列,第三行给出了后序序列。一行中的所有数字都以空格分隔。

    输出规格:
    对于每个测试用例,打印一行树的之字形序列。一行中的所有数字必须只有一个空格分开,并且行尾不能有额外的空格。

    思路:

    二叉树建立和遍历。用两个栈模拟zigzag遍历。

    ac代码:

    C++

    // pat1127.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    
    #include<iostream>
    #include<cstdio>
    #include<string>
    #include<algorithm>
    #include<queue>
    #include<vector>
    #include<cstring>
    #include<stdio.h>
    #include<map>
    #include<cmath>
    #include<stack>
    #include<unordered_map>
    #include<unordered_set>
    
    using namespace std;
    
    
    int n;
    int in[31];
    int post[31];
    int res[31];
    
    struct TreeNode
    {
    	int val;
    	TreeNode* left;
    	TreeNode* right;
    	TreeNode(int x) : val(x) , left(NULL) , right(NULL) {}
    };
    
    TreeNode* build(int ileft, int iright, int pleft, int pright)
    {
    	if (ileft > iright || pleft > pright) return NULL;
    
    	TreeNode* root = new TreeNode(post[pright]);
    	int cut = ileft;
    	while (cut <= iright && in[cut] != post[pright]) cut++;
    	 
    
    	root->left = build(ileft, cut - 1, pleft, pleft + cut - ileft - 1);
    	root->right = build(cut + 1, iright, pleft + cut - ileft, pright - 1);
    
    	return root;
    }
    
    int main()
    {
    	scanf("%d", &n);
    	for (int i = 0; i < n; i++) scanf("%d", &in[i]);
    	for (int i = 0; i < n; i++) scanf("%d", &post[i]);
    
    	TreeNode* root = build(0, n - 1, 0, n - 1);
    
    	//zigzag traversal
    	stack<TreeNode*> odd;
    	stack<TreeNode*> even;
    	odd.push(root);
    	int pos = 0;
    	while (!odd.empty() || !even.empty())
    	{
    		TreeNode* top;
    		if(even.empty())
    		{
    			while (!odd.empty())
    			{
    				top = odd.top();
    				odd.pop();
    				res[pos++] = top->val;
    				if (top->right) even.push(top->right);
    				if (top->left) even.push(top->left);				
    			}
    		}
    		else
    		{
    			while (!even.empty())
    			{
    				top = even.top();
    				even.pop();
    				res[pos++] = top->val;
    				if (top->left) odd.push(top->left);
    				if (top->right) odd.push(top->right);
    			}
    		}
    	}
    
    	for (int i = 0; i < n - 1; i++)
    		printf("%d ", res[i]);
    	if (n > 0) printf("%d
    ", res[n - 1]);
    
        return 0;
    }
    
    
    
  • 相关阅读:
    sql注入漏洞与防范
    微信小程序-工具,弹出当前系统代理不是安全代理处理方法
    微信小程序-02 小程序关注组件
    微信小程序-01 小数保留二位
    http 转hhttps
    php 函数-ksort
    iOS 原生二维码扫描
    iOS 打包错误 all-product-headers.yaml' not found
    iOS Tableview点击cell 会往上跳
    WKWebView 使用
  • 原文地址:https://www.cnblogs.com/weedboy/p/7354335.html
Copyright © 2020-2023  润新知