Convert Sorted Array to Binary Search Tree

Source: Internet
Author: User

Given an array where elements is sorted in ascending order, convert it to a height balanced BST.

The explanation of the complete copy from ref, thanks!

The following:

First review what is a two-fork search tree (quoted from Wikipedia):

The two-fork search tree (binary searchtrees), also called ordered Binary tree (ordered binary tree), sorts the binary trees (sorted binary), Refers to an empty tree or a two-fork tree with the following properties:

    1. If the left subtree of any node is not empty, the value of all nodes on the left subtree is less than the value of its root node;
    2. The right subtree of any node is not empty, then the value of all nodes on the right subtree is greater than the value of its root node;
    3. The left and right subtrees of any node are also two-fork lookup trees, respectively.

Then review what is the balanced binary tree (quoted 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 are not more than 1.

The workaround is to select the point to construct the root node, and then recursively construct the Saozi right subtree.

Tree Construction Basic Problem http://www.cnblogs.com/springfor/p/3879823.html

 Public classSolution { PublicTreeNode Sortedarraytobst (int[] nums) {        if(nums==NULL|| nums.length==0)return NULL; returnHelper (nums, 0, Nums.length-1); }     PublicTreeNode Helper (int[] num,intLowintHigh ) {        if(Low>high)return NULL; intMid = (Low+high)/2; TreeNode Root=NewTreeNode (Num[mid]); Root.left= Helper (Num,low, mid-1); Root.right= Helper (num, mid+1, high); returnRoot; }}

Convert Sorted Array to Binary Search Tree

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.