Convert an ordered array to a two-fork search tree

Source: Internet
Author: User

Problem Description:

Converts an ordered array in ascending order to a highly balanced binary search tree.

In the subject, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.

Example:

Given an ordered array: [ -10,-3,0,5,9], one possible answer is: [0,-3,9,-10,null,5], which can represent the following highly balanced binary search tree:      0     /    -3   9   /   /-10  5

Problem Solving Ideas:

The array is divided into three parts with the most intermediate values of the array: the left half, the middle value, and the right half part;

Constructs the node with the middle value, the left half of the array constructs the left sub-tree of the node, right half right subtree;

Repeat for the left half of the array and the right part.

Implementation code:

    Private StaticTreeNode Test (intNums[],intLointhi) {        if(Lo > Hi)return NULL; if(lo = hi)return NewTreeNode (Nums[lo]); intMid = lo + (Hi-lo)/2; TreeNode node=NewTreeNode (Nums[mid]); Node.left= Test (Nums, lo, mid-1); Node.right= Test (Nums, mid+1, HI); returnnode; }     Public StaticTreeNode Sortedarraytobst (intnums[]) {        returnTest (nums, 0, Nums.length-1); }

Convert an ordered array to a two-fork 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.