
Figure 1
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.
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.
6 Push 1 Push 2 Push 3 Pop Pop Push 4 Pop Pop Push 5 Push 6 Pop Pop
3 4 2 6 5 1
import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; class Tree { int val; Tree left; Tree right; public Tree(int val) { this.val = val; } public Tree() {} } public class Main { public static void postorder(Tree root, ArrayList list) { if (root != null) { postorder(root.left, list); postorder(root.right, list); list.add(root.val); } } public static void main(String args[]) { ArrayList list = new ArrayList(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //input N nodes Stack stack = new Stack(); String str = new String(""); Tree[] root = new Tree[n + 1]; int index = 0; int popVal = -1; for (int i = 0; i < 2 * n; ++i) { str = sc.next(); if (str.equals("Push")) { int value = sc.nextInt(); if (i == 0) { root[++index] = new Tree(value); } else if (i != 0 && popVal == -1) { root[(Integer) stack.peek()].left = root[++index] = new Tree(value); } if (popVal != -1) { root[popVal].right = root[++index] = new Tree(value); } stack.push(index); popVal = -1; } else { popVal = (Integer) stack.peek(); stack.pop(); } } postorder(root[1], list); for (int i = 0; i < list.size(); ++i) { if (i != list.size() - 1) System.out.print(list.get(i) + " "); else System.out.print(list.get(i)); } } }
step one: 首先根据输入,构造出原树的结构。
step two: 后序遍历原树。
关于第一步,需要观察Push和Pop,找出构造原树的方法:
每次Push相当于插入节点,Pop相当于回朔,为了便于回朔的实现,根据最后Pop出的节点的 Id,从已经构造的原树中查找应该回朔到的节点。
关于第二步,如果有n个节点,需要输出n-1个空格,经过观察发现,打印每个节点时,后面跟一个空格,根节点除外,这样就可以打印符合要求的结果,所以只需要能判断是否为根节点即可。
代码如下: