[leedcode 105] Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //The preorder and inorder traversals for the binary tree above is:
     /*   preorder = {7,10,4,3,1,2,8,11}
        inorder = {4,10,3,1,7,11,8,2}

        The first node in preorder alwasy the root of the tree. We can break the tree like:
        1st round:
        preorder:  {7}, {10,4,3,1}, {2,8,11}
        inorder:     {4,10,3,1}, {7}, {11, 8,2}
        可以发现,一趟遍历可以将数组一份为二,分别对应左子树集合和右子树集合
        使用preorder数组定位跟节点,利用inorder数组分左右子树。
        关键点:
        1 定位每层的根节点
        2 计算好offset
        注意getTree函数的定义*/
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length!=inorder.length||preorder.length==0) return null;
        return getTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    TreeNode getTree(int[] preorder,int left1,int right1,int[] inorder,int left2,int right2){
        if(left1>right1) return null;
        if(left2>right2) return null;
        int temp=preorder[left1];
        TreeNode node=new TreeNode(temp);
        int index=left2;
        for(;index<=right2;index++){
            if(inorder[index]==temp)break;
        }
        int len=index-left2;
        node.left=getTree(preorder,left1+1,left1+len,inorder,left2,index-1);
        node.right=getTree(preorder,left1+len+1,right1,inorder,index+1,right2);
        return node;
    }
}

 

你可能感兴趣的:(binary)