根据前序遍历和后续遍历建立二叉树

来源:互联网 发布:linux php5.6编译参数 编辑:程序博客网 时间:2024/05/01 15:42

前序遍历结果:1,2,4,9,7,3,5,6,8(根,左,右)
中序遍历结果:9,4,7,2,1,5,3,8,6(左,根,右)
前序遍历是先遍历根节点;中序遍历是先遍历左节点,再遍历根节点,最后是遍历右节点。可见在中序遍历当中,通过根节点将数组分为左右两部分,而根节点可以通过前序遍历中找到。如果根节点没有左右孩子,则可以直接返回给上一个节点,如果有递归划分。
比如:通过根节点1,将中序结果划分为(9,4,7,2)和(5,3,8,6),接着遍历前序下一个节点2,对(9,4,7,2)进行划分(9,4,7)和(),接着…..
具体代码如下:
BinartTree.java

package com.xll.binaryTree;public class BinaryTree {    /**记录遍历到前缀遍历结果数组的位置*/    private int pre = 0;    /**树的根节点*/    private Node root = null;    private int[] preR = null;    private int[] midR = null;    public BinaryTree(){        }    /**     *通过前序遍历和中序遍历结果构建二叉树     *     *@param preR 前缀遍历结果     *@param midR 后缀遍历结果     */    public void constructTree(int[] preR , int[] midR){        this.preR = preR;        this.midR = midR;        if(preR == null || midR == null){            System.out.println("前序结果或中序结果有问题");            return;        }        else if(preR.length > midR.length || midR.length > preR.length){            System.out.println("长度不一致");            return;        }        root = constructTreeCore(0 , midR.length - 1);    }    /**     *重构二叉树核心代码块,是从左到右至下而上构建     *比如前缀遍历结果是:1,2,4,7,3,5,6,8,     *先构建完7左右孩子,在构建4左右孩子...到1,     *这时已经构建完根节点1的左子树了,构建右子树     *原理一样     *     *@param midStart 数组midR下标(起始)     *@param midEnd 数组midR下标(结束)     */    public Node constructTreeCore(int midStart , int midEnd){        int rootValue = preR[pre];        int sepIndex = 0; //根节点在中序遍历中位置        Node root = new Node();        root.data = rootValue;        root.leftNode = root.rightNode = null;        for(int i = midStart ; i <= midEnd ; i++){            if(midR[i] == rootValue){                sepIndex = i;                break;            }        }        if(midStart == midEnd){            return root;        }        if((sepIndex - 1 - midStart) >= 0){            ++pre;            root.leftNode = constructTreeCore(midStart , sepIndex - 1);        }        if(sepIndex + 1 <= midEnd){            ++pre;            root.rightNode = constructTreeCore(sepIndex + 1 , midEnd);        }        return root;    }}

Node.java

package com.xll.binaryTree;public class Node {    public int data;    public Node leftNode;    public Node rightNode;    public Node(int data){        this.data = data;        this.leftNode = null;        this.rightNode = null;    }    public Node(){    }}

Main.java

package com.xll.binaryTree;public class Main {    public static void main(String[] args){        BinaryTree bt = new BinaryTree();        int[] preR = new int[]{1 , 2 , 4 , 9 , 7 , 3 , 5 , 6 , 8};        int[] midR = new int[]{9 , 4 , 7 , 2 , 1 , 5 , 3 , 8 , 6};        bt.constructTree(preR, midR);    }}
0 0