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 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {

        int len = preorder.length;
        if( len == 0)
            return null;
        return helper(preorder,0,len-1,inorder,0,len-1);

        
    }



    public TreeNode helper( int[] preorder,int pre_start,int pre_end,int[] inorder,int in_start,int in_end){

        if( pre_start > pre_end || in_start > in_end )
            return null;
        TreeNode node = new TreeNode(preorder[pre_start]);


        int size = 0;
        for( int i = in_start;i<=in_end && inorder[i] != preorder[pre_start];i++,size++)
            ;
        node.left = helper(preorder,pre_start+1,pre_start+size,inorder,in_start,in_start+size-1);

        node.right = helper(preorder,pre_start+size+1,pre_end,inorder,in_start+size+1,in_end);

        return node;


    }
}

速度不算快,速度最快的答案也进行了参考。

 

并不是算法有多好,只是他在

for( int i = in_start;i<=in_end && inorder[i] != preorder[pre_start];i++,size++)
            ;

这里遍历的时候选择了从后向前遍历,由于测试数据的特殊性,导致了其答案的快速性。