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

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 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){
            i++;
        }
        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;
    }
    
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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