Convert Sorted Array to Binary Search Tree
Given an array where elements is sorted in ascending order, convert it to a height balanced BST.
Problem Solving Ideas:
Test instructions is a binary lookup tree that constructs an ordered array. Relatively simple, recursive method can be, the middle element as the root node, the first half as the left child tree, right half as the right child tree.
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public: treenode* sortedarraytobst (vector<int>& nums) { return Sortedarraytobsthelper (nums, 0, Nums.size ()-1); } treenode* Sortedarraytobsthelper (vector<int>& nums, int start, int end) { if (start>end) { return NULL; } int middle = (start+end)/2; treenode* root = new TreeNode (Nums[middle]); Root->left = Sortedarraytobsthelper (Nums, start, middle-1); Root->right = Sortedarraytobsthelper (nums, Middle + 1, end); return root; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Convert Sorted Array to Binary Search Tree