it_worker365

   ::  ::  ::  ::  :: 管理

首先根据定义,先序的第一个元素为根节点,由于规定元素没有重复,所以可以根据根节点数值来将中序遍历数组中左右子数分开。

同时根据左右子数的个数继续拆分对应的先序数组,递归左右子树得到结果

/**
 * Created by itworker365 on 5/12/2017.
 */
public class RebuildBTree {
    //有一个前提是元素无重复
    public static void main(String[] args) {
        //根左右
        int[] preTrace = {1,2,4,7,3,5,6,8};
        //左根右
        int[] midTrace = {4,7,2,1,5,3,8,6};
        RebuildBTree rebuildBTree = new RebuildBTree();
        TreeNode treeNode = rebuildBTree.reConstructBinaryTree(preTrace, midTrace);
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre.length == 0 || in.length == 0) {
            return null;
        }
        return reConstructBinaryTree111(pre, 0, pre.length - 1, in, 0, in.length - 1);
    }
    public TreeNode reConstructBinaryTree111(int [] pre,int pstart, int pend, int [] in, int istart, int iend) {
        if (pstart > pend || istart > iend) {
            return null;
        }
        TreeNode root=new TreeNode(pre[pstart]);
        //首先由先序遍历知道第一个元素肯定是根元素,遍历中序找,找到根节点
        //将中序结果分为两个子子数,根据元素个数同时拆分先序数组,分别构建左右子树
        for(int i = istart; i <= iend; i++)
            if(in[i] == pre[pstart]){
                root.left = reConstructBinaryTree111(pre, pstart + 1, pstart + i - istart, in, istart, i - 1);
                root.right = reConstructBinaryTree111(pre, i - istart + pstart + 1, pend, in, i + 1, iend);
            }
        return root;
    }
}
class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) {
        val = x;
    }

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

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

 

posted on 2017-05-12 15:08  it_worker365  阅读(1061)  评论(0编辑  收藏  举报