给出二叉树的中序和后序遍历,构建出二叉树

假设二叉树中序遍历为:

int[] inOrder = { 4, 2, 5, 1, 6, 3, 7 };

后序遍历为

int[] postOrder = { 4, 5, 2, 6, 7, 3, 1 };

那么,如何构建还原出这颗二叉树?类似问题还有:给出二叉树的先序和中序遍历如何还原出二叉树

算法思想:

  • 后序遍历中的最后一个元素为二叉树的根节点,这里是数字1
  • 在中序遍历集合中查找数字1,记作位置i,注意i的左边是左子树,右边是右子树
  • 假设在步骤2中,有X个元素在i的左侧,那么从后序遍历集合中取前X个元素,得到的结果子集合即为左子树的后序遍历,类似的,i的右侧有Y个元素,那么,从后续遍历集合中取接下来的Y个元素,得到的结果即为右子树的后序遍历
  • 通过步骤2和步骤3构建出根节点的左子树和右子树

在这里插入图片描述

算法实现:

public class InorderPostOrderToTree {

    public static int pIndex = 0;

    public Node makeBTree(int[] inOrder, int[] postOrder, int iStart, int iEnd,
                          int postStart, int postEnd) {
        if (iStart > iEnd || postEnd > postEnd) {
            return null;
        }

        int rootValue = postOrder[postEnd];
        Node root = new Node(rootValue);
        pIndex++;

        if (iStart == iEnd) {
            return root;
        }
        int index = getInorderIndex(inOrder, iStart, iEnd, root.data);
        root.left = makeBTree(inOrder, postOrder, iStart, index - 1, postStart,
                postStart + index - (iStart + 1));
        root.right = makeBTree(inOrder, postOrder, index + 1, iEnd, postStart
                + index - iStart, postEnd - 1);
        return root;
    }

    public int getInorderIndex(int[] inOrder, int start, int end, int data) {
        for (int i = start; i <= end; i++) {
            if (inOrder[i] == data) {
                return i;
            }
        }
        return -1;
    }

    public void printInorder(Node root) {
        if (root != null) {
            printInorder(root.left);
            System.out.print(root.data + " ");
            printInorder(root.right);
        }
    }

    public static void main(String[] args) {
        int[] inOrder = {4, 2, 5, 1, 6, 3, 7};
        int[] postOrder = {4, 5, 2, 6, 7, 3, 1};
        InorderPostOrderToTree i = new InorderPostOrderToTree();
        Node x = i.makeBTree(inOrder, postOrder, 0, inOrder.length - 1, 0,
                postOrder.length - 1);
        System.out.println("inorder traversal of constructed tree:");
        i.printInorder(x);

    }
}

class Node {
    int data;
    Node left;
    Node right;

    public Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

输出结果

inorder traversal of constructed tree:
4 2 5 1 6 3 7 

https://algorithms.tutorialhorizon.com/construct-a-binary-tree-from-given-inorder-and-postorder-traversal/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值