Lintcode-easy-convert Sorted Array to Binary Search Tree with Minimal Height

Source: Internet
Author: User

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 and return any of them.

Thinking more direct, the middle number as root, the first half as the left subtree, the latter half as the right sub-tree

/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/  Public classSolution {/**     * @paramA:an Integer Array *@return: A tree node*/     PublicTreeNode Sortedarraytobst (int[] A) {//Write your code here        if(A = =NULL|| A.length = = 0)            return NULL; TreeNode Root= Gettree (A, 0, A.length-1); returnRoot; }           PublicTreeNode Gettree (int[] A,intStartintend) {        if(Start >end)return NULL; intMID = start + (End-start)/2; TreeNode Root=NewTreeNode (A[mid]); TreeNode Left= Gettree (A, start, mid-1); TreeNode Right= Gettree (A, Mid + 1, end); Root.left=Left ; Root.right=Right ; returnRoot; }    }

Lintcode-easy-convert Sorted Array to Binary Search Tree with Minimal Height

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.