PAT甲级1086 Tree Traversals Again

31 篇文章 0 订阅

本题考查

二叉树、中序遍历

思路

思路一句话:“根据二叉树中序遍历非递归代码生成二叉树并对其进行后序遍历”
如何根据二叉树中序遍历非递归代码生成二叉树?
建立两个变量preCal与pre分别记录上一次操作的类型与操作的结点索引。
分两种情况讨论:

  • 如果当前操作是“push”的话
如果上一次的操作是push,则本次push结点是上个操作结点的左孩子
如果上一次的操作是pop,则本次push结点是上个pop出的结点的右孩子
  • 如果当前操作是“pop”的话
更新preCal与pre的值

AC代码

import java.util.Scanner;
import java.util.Stack;

public class Main {

	static String result = "";
	
	static class Node {
		int key;
		Node leftChild;
		Node rightChild;
		public Node() {
			this.key = -1;
			this.leftChild = null;
			this.rightChild = null;
		}
	}
	
	static void postOrder(Node root) {
		if(root.leftChild != null)
			postOrder(root.leftChild);
		if(root.rightChild != null)
			postOrder(root.rightChild);
		result += root.key + " ";
	}
	
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();
		Scanner scaner = new Scanner(System.in);
		int round = scaner.nextInt();
		Node[] tree = new Node[round+1];
		for (int i = 0; i < round+1; i++) {
			tree[i] = new Node();
		}
		int pre = -1;
		String preCal = "";
		int root = -1;
		for (int i = 0; i < 2 * round; i++) {
			String cal = scaner.next();
			if(cal.equals("Push")) {
				int temp = scaner.nextInt();
				stack.push(temp);
				tree[temp].key = temp;
				if(pre == -1) {
					root = temp;
				}
				else {
					if(preCal.equals("Push"))
						tree[pre].leftChild = tree[temp];
					else
						tree[pre].rightChild = tree[temp];
				}
				preCal = cal;
				pre = temp;
			}
			else {
				preCal = cal;
				pre = stack.pop();
			}
		}
		scaner.close();
		postOrder(tree[root]);
		System.out.println(result.trim());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值