Leetcode: convert_sorted_array_to_binary_search_tree

Source: Internet
Author: User

I. Question

Converts an sorted array into a binary search tree.

Ii. Analysis

In BST, the central traversal is a sorted-array, which is then constructed into a BST. The middle element is used as the root node. The left and right sides of this node are left and right subtree respectively. Do this recursively.

 

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode *sortedArrayToBST(vector<int> &num) {    return addNode(num, 0, num.size()-1);   }   TreeNode *addNode(vector<int> &num, int start, int end){    if(start > end) return NULL;        int mid = (start + end)/2;    TreeNode *root = new TreeNode(num[mid]);    root->left = addNode(num, start, mid-1);    root->right = addNode(num, mid+1, end);    return root;   }};


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