码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode easy]Convert Sorted Array to Binary Search Tree With Minimal Height

时间:2015-12-01 07:10:43      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 

//////////////////////

二叉查找树Binary Search Tree),也称有序二叉树(ordered binary tree),排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树

  1. 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
  2. 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
  3. 任意节点的左、右子树也分别为二叉查找树。

 

 

平衡二叉树(引自GeekforGeek):

An empty tree is height-balanced. A non-empty binary tree T is balanced if:
   1) Left subtree of T is balanced
   2) Right subtree of T is balanced
   3) The difference between heights of left subtree and right subtree is not more than 1.  

 ////////////////////////////////////////////////////

/**
 * 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.length==0) return null;
        
        return buildTree(A,0,A.length-1);
    }  
    
    public TreeNode buildTree(int[] A, int low, int high)
    {
        if(low>high) return null;
        int mid=(low+high)/2;
        TreeNode node=new TreeNode(A[mid]);
        node.left=buildTree(A,low,mid-1);
        node.right=buildTree(A,mid+1,high);
        
        return node;
        
    }
}

 

[lintcode easy]Convert Sorted Array to Binary Search Tree With Minimal Height

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5008998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!