letecode [108] - Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
      0
     / \
   -3   9
   /   /
 -10  5
 

Subject to the effect:

  Given array in ascending order, to convert it into a balanced binary tree search.

Understanding:

  According to the definition of the binary tree search, the result array traversal order in a binary tree. Should the binary tree is a balanced binary tree. Binary output may result.

  Using recursive thought, the intermediate array is the root node, but also viewed as an array of sequences around the left and right sub-tree, the leaf nodes to the recursion.

  Thereby constructing a binary tree, but also to ensure that the construction of both a balanced binary tree binary tree is a binary tree search.

Code C ++:

/**
 * 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* AnSortedArrayToBST(vector<int>& nums,int left,int right) {
        if(left > right) return NULL;
        int mid = (right-left)/2+left;
        TreeNode* node = new TreeNode(nums[mid]);
        node->left = AnSortedArrayToBST(nums,left,mid-1);
        node->right = AnSortedArrayToBST(nums,mid+1,right);
        return node;
    }
    
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return NULL;
        return AnSortedArrayToBST(nums,0,n-1);
    }
};

operation result:

  When executed with:  28 MS   memory consumption:  21.2 MB

Guess you like

Origin www.cnblogs.com/lpomeloz/p/10993620.html