lintcode-medium-Construct Binary Tree from Preorder and Inorder Traversal

Posted 哥布林工程师

tags:

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

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

Given in-order [1,2,3] and pre-order [2,1,3], return a tree:

  2
 / 1   3

 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        
        if(preorder == null || preorder.length == 0)
            return null;
        
        int size = preorder.length;
        
        TreeNode root = build(preorder, 0, size - 1, inorder, 0, size - 1);
        
        return root;
    }
    
    public TreeNode build(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 root = new TreeNode(preorder[pre_start]);
        
        int k = in_start;
        for(; k <= in_end; k++){
            if(inorder[k] == preorder[pre_start])
                break;
        }
        
        TreeNode left = build(preorder, pre_start + 1, pre_start + k - in_start, inorder, in_start, k - 1);
        TreeNode right = build(preorder, pre_start + k - in_start + 1, pre_end, inorder, k + 1, in_end);
        
        root.left = left;
        root.right = right;
        
        return root;
    }
    
}

 

 

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