根据遍历序列确定二叉树

  • 确定二叉树的方法

先序加中序或者后序加中序可以确定唯一一棵二叉树

1、首先来看后序加中序
①思想:
由后序遍历特征,根结点必在后序序列尾部,则可以确定根结点
又中序遍历序列中,根结点必在中部,左边为左子树,右边为右子树。
两个子树再利用上述方法,不断确定根结点。

②代码实现

public TreeNode buildTree(int[] inorder, int[] postorder) {

        int inLength = inorder.length;
        int postLength  = postorder.length;
        return buildTree(postorder, 0, postLength - 1, inorder, 0 , inLength - 1);
    } 
    public TreeNode buildTree(int[] post, int postStart, int postEnd, int[] in, int inStart, int inEnd) {

        if(inStart > inEnd || postStart > postEnd) {
            return null;
        }

        int rootVal = post[postEnd];
        int rootIndex = 0;

        for(int i = inStart; i < inEnd; i++) {

            if(in[i] == rootVal) {
                rootIndex = i;
                break;
            }
        }

        int len = rootIndex - inStart;
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(post, postStart, postStart + len - 1, in, inStart, rootIndex - 1);
        root.right = buildTree(post, postStart + len, postEnd - 1, in, rootIndex + 1, inEnd);
        return root;
    }

2、先序加中序确定二叉树
①思想:先序确定根结点,中序确定左右子树。

②代码实现

public TreeNode builder(int[] preorder, int[] inorder) {

        int preLength = preorder.length;
        int inLength = inorder.length;

        return buildTree(preorder, 0, preLength  -1, inorder, 0, inLength - 1);
    }
    public TreeNode buildTree(int[] pre, int preStart, int preEnd, int[] in , int inStart, int inEnd) {

        if(inStart > inEnd || preStart > preEnd) {
            return null;
        }
        int rootVal = pre[preStart];
        int rootIndex = 0;

        for(int i = inStart; i <= inEnd; i++) {

            if(in[i] == rootVal ) {
                rootIndex = i;
                break;
            }
        }
        int len = rootIndex - inStart;
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(pre, preStart + 1, preStart + len, in, inStart, rootIndex - 1);
        root.right = buildTree(pre, preStart + len + 1, preEnd, in , rootIndex  + 1, inEnd);
        return root;
    }

3、总结
有点难。。。

posted on 2018-08-22 14:24  的先生在打码  阅读(498)  评论(0编辑  收藏  举报

导航