[Simple Algorithm] 30. Convert an ordered array to a binary search tree

topic:

Converts an ascending sorted array into a height-balanced binary search tree.

In this question, a height-balanced binary tree means that the absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1 .

Example:

Given an ordered array: [ - 10 ,- 3 , 0 , 5 , 9 ],

A possible answer is: [ 0 ,- 3 , 9 ,- 10 , null , 5 ], which can represent the following height-balanced binary search tree:

      0
     / \
   -3   9
   /   /
 -10  5

The solution to the problem is as follows:

Each time the data in the middle of the array is taken as the root node, the array is divided into half and the second half, the first half constitutes the left subtree of the BST, and the second half constitutes the right subtree of the BST, recursively in turn.

code show as below:

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325250473&siteId=291194637