LeetCode Note: Convert Sorted Array to Binary Search Tree
I. Description
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Ii. Question Analysis
By traversing the binary search tree in the middle order, you can get an array in the ascending order. Therefore, an sorted array can be seen as an array in the middle order traversal, to obtain a highly balanced binary search tree, you can make the number of left and right Subtrees as equal as possible. Therefore, the array can be divided into two sub-arrays by the binary method. The middle value is used as the parent node, the Child array on the left is used as the left sub-tree, and the Child array on the right is used as the right sub-tree for recursion, in this way, you can obtain a highly balanced binary search tree.
Iii. Sample Code
#include
#include
using namespace std;struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution{public: TreeNode* sortedArrayToBST(vector
& nums) { return generateBST(0, num.size() - 1, num); }private: TreeNode* generateBST(int left, int right, vector
& num) { if (left > right) return nullptr; else if (left == right) return new TreeNode(num[left]); else { int mid = (left + right) / 2; TreeNode* node = new TreeNode(num[mid]); node->left = generateBST(left, mid - 1, num); node->right = generateBST(mid + 1, right, num); return node; } } };
Iv. Summary
The trick of this question is that the central traversal of the Binary Search Tree is an array in ascending order. Therefore, this question is to construct a binary search tree based on the central order of a binary search tree, because the height balance is required, you can consider the two Subtrees with the same number of nodes, so that you can get a unique Binary Search Tree.