lintcode-easy-Convert Sorted Array to Binary Search Tree with Minimal Height

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Convert Sorted Array to Binary Search Tree with Minimal Height相关的知识,希望对你有一定的参考价值。

Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.

 

Example

Given [1,2,3,4,5,6,7], return

     4
   /     2     6
 / \    / 1   3  5   7
Note

There may exist multiple valid solutions, return any of them.

 

思路比较直接,中间的数作为root,前一半作为左子树,后一半作为右子树

/**
 * 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 A: an integer array
     * @return: a tree node
     */
    public TreeNode sortedArrayToBST(int[] A) {  
        // write your code here
        if(A == null || A.length == 0)
            return null;
        
        TreeNode root = getTree(A, 0, A.length - 1);
        
        return root;
    }  
    
    public TreeNode getTree(int[] A, int start, int end){
        if(start > end)
            return null;
            
        int mid = start + (end - start) / 2;
        
        TreeNode root = new TreeNode(A[mid]);
        
        TreeNode left = getTree(A, start, mid - 1);
        TreeNode right = getTree(A, mid + 1, end);
        
        root.left = left;
        root.right = right;
        
        return root;
    }
    
}

 

以上是关于lintcode-easy-Convert Sorted Array to Binary Search Tree with Minimal Height的主要内容,如果未能解决你的问题,请参考以下文章

SOR迭代法实验报告c语言,数学实验“线性方程组的J-迭代,GS-迭代,SOR-迭代解法”实验报告(内含matlab程序代码).doc...

spring中AutowiredAnnotationBeanPostProcessor的注册时机

spring框架_@AutoWiredAnnotationBeanPostProcessor执行分析

SOR和SSOR迭代

Spring 注解原理AutowiredAnnotationBeanPostProcessor:@Autowired @Value @Inject @Lookup

Topological Sor-207. Course Schedule