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.

package com.cn.cya.constructbinarytreefrompreorderandinordertraversal;
class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
 }
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null||preorder.length==0||inorder==null||inorder.length==0||preorder.length!=inorder.length)
            return null;
    
        
        return build_Tree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    public TreeNode buildTree(int[] preorder,int prestar,int preend,int[] inorder,int instar,int inend){
        if(prestar>preend||instar>inend)return null;
        int root_val=preorder[prestar];
        TreeNode root=new TreeNode(root_val);
        int index=instar;//preorder中第一个元素在中序遍历中的位置
        for (;index < inend&&inorder[index]!=root_val; index++) {    
        }
        root.left=buildTree(preorder,prestar+1, prestar+index-instar, inorder,instar,index-1);
        root.right=buildTree(preorder,prestar+index-instar+1, preend, inorder,index+1,inend);
        return root;
    }
  
}
原文地址:https://www.cnblogs.com/softwarewebdesign/p/5517830.html