1265: 输出二叉树

题目

Description

我们知道二叉树的先序序列和中序序列或者是中序和后序能够唯一确定一颗二叉树。现在给一颗二叉树的先序序列和中序序列,要求输出它的后序序列。

Input

多组测试数据,每组测试数据格式如下:
第一行为先序序列
第二行为中序序列

Output

 输出该二叉树的后序序列。

Sample Input

ABFCDGHEI
BFAGDHCIE
Sample Output

FBGHDIECA

代码块

import java.util.Scanner;

public class Main {
    /**
     * 根据前序遍历和中序遍历重建二叉树子树
     * 
     * @param preOrder
     *            前序遍历数组
     * @param start
     *            子树起始位置
     * @param inOrder
     *            中序遍历数组
     * @param end
     *            中序遍历结束位置
     * @param length
     *            子树节点树
     * @return 子树的根节点
     */
    public static void main(String[] args) {
        Scanner cn = new Scanner(System.in);
        String str1 = cn.next();
        String str2 = cn.next();
        char[] preOrder = str1.toCharArray();
        char[] inOrder = str2.toCharArray();
        Node root = buildTree(preOrder, 0, inOrder, inOrder.length - 1,
                inOrder.length);
        postorder(root);
        System.out.println();
        cn.close();
    }

    public static void visit(Node p) {
        System.out.print(p.getValue());
    }

    public static Node buildTree(char[] preOrder, int start, char[] inOrder,
            int end, int length) {
        // 参数验证
        if (preOrder == null || preOrder.length == 0 || inOrder == null
                || inOrder.length == 0 || length <= 0) {
            return null;
        }
        // 建立子树根节点
        char value = preOrder[start];
        Node root = new Node();
        root.value = value;

        // 递归终止条件:子树只有一个节点
        if (length == 1)
            return root;
        // 分拆子树的左子树和右子树
        int i = 0;
        while (i < length) {
            if (value == inOrder[end - i]) {
                break;
            }
            i++;
        }
        // 建立子树的左子树
        root.left = buildTree(preOrder, start + 1, inOrder, end - i - 1, length
                - 1 - i);
        // 建立子树的右子树
        root.right = buildTree(preOrder, start + length - i, inOrder, end, i);

        return root;
    }

    public static void postorder(Node root) {
        if (root != null) {
            postorder(root.getLeft());
            postorder(root.getRight());
            visit(root);
        }
    }

}

class Node {
    Node left = null;
    Node right = null;
    char value;

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public char getValue() {
        return value;
    }

    public void setValue(char value) {
        this.value = value;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值