Construct Binary Tree from Preorder and Inorder Traversal, Leetcode 解题笔记

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

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


 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
    public TreeNode build(int[] preorder, int[] inorder, int pre_s, int pre_e, int in_s, int in_e){
        if(pre_s > pre_e) return null;
        TreeNode root = new TreeNode(preorder[pre_s]);
        int i = in_s;
        while(i <= in_e && inorder[i] != root.val){
        int len = i-in_s;
        root.left = build(preorder, inorder, pre_s+1, pre_s+len, in_s, in_s+len);
        root.right = build(preorder, inorder, pre_s+len+1, pre_e, i+1, in_e);
        return root;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s