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