PTA数据结构-03-树3 Tree Traversals Again

一、题目

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.


Figure 1

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

 

二、解答

import java.util.*;

public class Main{
    static ArrayList<Integer> stack = new ArrayList<>();
    static int index = -1;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int len = Integer.parseInt(sc.nextLine());
        ArrayList<Integer> preOrder = new ArrayList<Integer>(len);
        ArrayList<Integer> inOrder = new ArrayList<Integer>(len);
        for (int i = 0; i < len * 2; i++) {
            String[] strs = sc.nextLine().split(" ");
            if (strs[0].equals("Push")) {
                int temp = Integer.parseInt(strs[1]);
                preOrder.add(temp);
                push(temp);
            } else if (strs[0].equals("Pop")) {
                inOrder.add(pop());
            }
        }
        //创建一棵树
        Node[] tree = new Node[len + 1];
        for (int i = 0; i < len+1; i++) { tree[i] = new Node();}
        createTree(preOrder, inOrder, tree);
        //将递归产生的后序遍历结果存放在res中
        List<Integer> res = new ArrayList<>();
        postOrder(preOrder.get(0), tree, res);
        res.add(preOrder.get(0));
        //输出结果
        String str = "";
        for (int num:res) str += num + " ";
        System.out.println(str.trim());
    }
    //list.subList(from,to)   得到的子列为从位置list[from]到位置list[to-1]
    public static void createTree(List<Integer> pre, List<Integer> in, Node[] tree){
        if (pre.size() > 1) {
            int len = pre.size();
            int father = pre.get(0);
            int fatherPos = in.indexOf(father);
            //获取子序列后递归实现根的查找
            List<Integer> leftSubPreOrder = null;
            List<Integer> rightSubPreOrder = null;
            List<Integer> leftSubInOrder = null;
            List<Integer> rightSubInOrder = null;
            //只有右子树
            if (fatherPos == 0) {
                tree[father].right = pre.get(1);
                rightSubPreOrder = pre.subList(1, len);
                rightSubInOrder = in.subList(1, len);
                createTree(rightSubPreOrder, rightSubInOrder, tree);
            }
            //只有左子树
            else if (fatherPos == len - 1) {
                tree[father].left = pre.get(1);
                leftSubPreOrder = pre.subList(1, len);
                leftSubInOrder = in.subList(0, len - 1);
                createTree(leftSubPreOrder, leftSubInOrder, tree);
            }
            //其他
            else {
                tree[father].left = pre.get(1);
                tree[father].right = pre.get(fatherPos + 1);
                leftSubPreOrder = pre.subList(1, fatherPos + 1);
                leftSubInOrder = in.subList(0, fatherPos);
                rightSubPreOrder = pre.subList(fatherPos + 1, len);
                rightSubInOrder = in.subList(fatherPos + 1, len);
                createTree(leftSubPreOrder, leftSubInOrder, tree);
                createTree(rightSubPreOrder, rightSubInOrder, tree);
            }
        }
    }
    //后序递归遍历
    public static void postOrder(int root, Node[] tree, List res){
        if (tree[root].left != -1) {
            postOrder(tree[root].left, tree, res);
            res.add(tree[root].left);
        }
        if (tree[root].right != -1) {
            postOrder(tree[root].right, tree, res);
            res.add(tree[root].right);
        }
    }
    public static void push(int num){
        stack.add(num);
        index++;
    }
    public static int pop(){
        return stack.remove(index--);
    }
}
class Node{
    int left = -1;
    int right = -1;
}

思路:

  1. 解题关键在于能够知道题目的考点:将题目给的输入理解为已知树的先序遍历(压入堆栈)和中序遍历(弹出堆栈)求树的后序遍历
  2. 如何将输入转化为先序遍历和中序遍历:使用list较为方便,不需要知道index,直接add,以及list方便在之后获取子序列
  3. 已知先序和中序如何构建一棵树:递归实现,根据先序和中序可以获得根、左右子序列的先序和中序遍历、左右儿子,特别小心只有左子树或者只有右子树的情况,以及子序列为只有一个叶节点的时候该如何处理
  4. 建好树后考虑如何后序遍历:递归实现

思考:

后序遍历还需要更熟练一下,以及试着写一下先序遍历和中序遍历
本题是否还有更简单的办法?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值