Leetcode converting an ordered array to a two-fork search tree

Source: Internet
Author: User

Topic:

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

In this problem, 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], a workable answer is: [0,-3,9,-10,null,5], which can be represented as the following highly balanced binary search tree:      0     /    -3   9   /   /-10  5

Idea: Using dichotomy to create a balanced binary tree, the root node is just the middle of the node, the root of the left subtree of the tree is the middle node of the left part of the array, the right subtree of the root node is the middle node of the right part of the data; The code execution results and examples give different results, but satisfy the balanced binary tree.

Code:

/** * Definition for a binary tree node.  * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *     TreeNode (int x) {val = x;} *}  */class Solution {public    TreeNode sortedarraytobst (int[] nums) {        if (nums = = NULL | | nums.length = = 0)            return null;        Return Gettree (nums,0,nums.length-1);    }        Public TreeNode gettree (int []nums,int l,int r) {        if (L <= r) {            int mid = (l+r)/2;            TreeNode node = new TreeNode (Nums[mid]);            Node.left = Gettree (nums,l,mid-1);            Node.right = Gettree (nums,mid+1,r);            return node;        } else{            return null;}}    }

Leetcode converting 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.