IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 数据结构与算法 -> Tree Traversals Again (25 分)java -> 正文阅读

[数据结构与算法]Tree Traversals Again (25 分)java

PTA7-5 Tree Traversals Again (25 分)java版

题目描述:
An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

阅读题目后我们发现入栈顺序正好是对该二叉树的先序遍历过程,出栈顺序是该二叉树的中序遍历过程。于是这个题的意思就是根据一个先序遍历和一个中序遍历的序列来恢复一棵二叉树,并且用后序遍历来输出它的节点值。
用题目中的例子来看,先序遍历:1 2 3 4 5 6
中序遍历:3 2 4 1 6 5
首先要找根节点,怎么找?就是在先序遍历中的第一个输出就是整颗二叉树的根节点,根据该根节点在中序遍历中找到相应的根节点位置,下标为[3],然后我们就可以根据中序遍历把数组分成两部分,左子树包括3,2,4,右子树包括6,5,根据左子树和右子树的个数我们就可以在先序遍历中同样划分出左子树和右子树来,即左子树:2,3,4,右子树:5,6
然后又可以在左右子树中分别找到根节点,再重复以上过程。
很显然这个过程要用递归实现,我尝试了两种方式,一个是每次递归调用都拷贝一份新的中序和先序的数组,另一个是在全部的递归调用中只用一份原始数组不进行拷贝,每次传入新的下标。第一种方式容易实现,第二种方式需要考虑清楚情况,否则很容易下标越界。

方法一:每次递归调用传入新的数组拷贝

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;

public class TreeTraversalsAgain {
	static int cnt = 0;

	public static TreeNode createTree(int[] pre, int[] in) {
		if (pre.length != in.length || pre.length < 1)
			return null;
		if (pre.length == 1)
			return new TreeNode(pre[0]);
		int r = pre[0];
		int ir = -1;
		for (int i = 0; i < in.length; i++) {
			if (in[i] == r) {
				ir = i;
				break;
			}
		}
		if (ir == -1)
			return null;
		TreeNode root = new TreeNode(r);
		int[] leftin = new int[ir];
		System.arraycopy(in, 0, leftin, 0, ir);
		int[] leftpre = new int[ir];
		System.arraycopy(pre, 1, leftpre, 0, ir);
		root.l = createTree(leftpre, leftin);

		int[] rightin = new int[in.length - 1 - ir];
		System.arraycopy(in, ir + 1, rightin, 0, in.length - 1 - ir);
		int[] rightpre = new int[in.length - 1 - ir];
		System.arraycopy(pre, ir + 1, rightpre, 0, in.length - 1 - ir);
		root.r = createTree(rightpre, rightin);

		return root;
	}

	public static void postOrder(TreeNode bt, int n) {
		if (bt != null) {
			postOrder(bt.l, n);
			postOrder(bt.r, n);
			if (cnt == n - 1) {
				System.out.print(bt.val);
			} else {
				System.out.print(bt.val + " ");
				cnt++;
			}
		}
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		int n = Integer.parseInt(str);
		String s[];
		Deque<Integer> stack = new LinkedList<Integer>();
		int[] pre = new int[n];
		int[] in = new int[n];
		int popc = 0;
		int pushc = 0;
		for (int i = 0; i < 2 * n; i++) {
			str = br.readLine();
			if (str.equals("Pop")) {
				in[popc++] = stack.pop();
			} else {
				s = str.split(" ");
				stack.push(Integer.parseInt(s[1]));
				pre[pushc++] = Integer.parseInt(s[1]);
			}
		}
		TreeNode root = createTree(pre, in);
		postOrder(root, n);
	}

}

class TreeNode {
	int val;
	TreeNode l;
	TreeNode r;

	TreeNode(int val) {
		this.val = val;
	}
}

方法二:每次递归调用传入新的下标

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Deque;
import java.util.LinkedList;

public class Main {
	static int cnt = 0;
	public static TreeNode createTree(int [] pre,int [] in,int pres,int pree,int ins,int ine)
	{
		if(pres>=pre.length)//存在pres超过数组最大下标的情况,因为可能会出现只有左子树,没有右子树的情况
			return null;
		if(pree==pres)
			return new TreeNode(pre[pres]);//当pres和pree相等时,生成该节点
		int r = pre[pres];
		TreeNode root = new TreeNode(r);
		int ir = -1;
		int tem = 0;//用来记录左子树节点的个数
		for(int i=ins;i<=ine;i++)
		{
			if(in[i]==r)
			{
				ir = i;
				break;
			}
			else
				tem++;
		}
		if(ir==-1)
			return null;
		root.l = createTree(pre, in, pres+1, pres+tem, ins, ir-1);
		root.r = createTree(pre, in, pres+tem+1, pree, ir+1, ine);
		return root;
	}
	public static void postOrder(TreeNode bt, int n)
	{
		if(bt!=null)
		{
			postOrder(bt.l, n);
			postOrder(bt.r, n);
			if(cnt!=n-1)
			{
				System.out.print(bt.val+" ");
				cnt++;
			}
			else
				System.out.print(bt.val);
		}
	}
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		int n = Integer.parseInt(str);
		int [] pre = new int [n];
		int [] in = new int [n];
		int prec = 0;
		int inc = 0;
		Deque<Integer> stack = new LinkedList<Integer>();
		for(int i=0;i<2*n;i++)
		{
			str = br.readLine();
			if(str.equals("Pop"))
			{
				in[inc++] = stack.pop();
			}
			else
			{
				String [] s = str.split(" ");
				int val = Integer.parseInt(s[1]);
				pre[prec++] = val;
				stack.push(val);
			}
		}
		TreeNode root = createTree(pre, in, 0, n-1, 0, n-1);
		postOrder(root, n);
	}
	
}
class TreeNode{
	int val;
	TreeNode l;
	TreeNode r;
	TreeNode(int val)
	{
		this.val = val;
	}
}
  数据结构与算法 最新文章
【力扣106】 从中序与后续遍历序列构造二叉
leetcode 322 零钱兑换
哈希的应用:海量数据处理
动态规划|最短Hamilton路径
华为机试_HJ41 称砝码【中等】【menset】【
【C与数据结构】——寒假提高每日练习Day1
基础算法——堆排序
2023王道数据结构线性表--单链表课后习题部
LeetCode 之 反转链表的一部分
【题解】lintcode必刷50题<有效的括号序列
上一篇文章      下一篇文章      查看所有文章
加:2021-07-31 16:53:22  更:2021-07-31 16:55:46 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/7 23:12:02-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码