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 {
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)
return null;
if(pree==pres)
return new TreeNode(pre[pres]);
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{
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;
}
}
|