leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java

Posted xiaoba1203

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java相关的知识,希望对你有一定的参考价值。

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++)
            ;

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

 




以上是关于leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-105-Construct Binary Tree from Preorder and Inorder Traversal

一天一道LeetCode#105. Construct Binary Tree from Preorder and Inorder Traversal

LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal

leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal ----- java

leetcode105:Construct Binary Tree from Preorder and Inorder Traversal

LeetCode105 Construct Binary Tree from Preorder and Inorder Traversal