欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

108. Convert Sorted Array to Binary Search Tree

程序员文章站 2022-05-18 19:36:16
...

problems:
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

tips:
参考博客:https://blog.csdn.net/u012814856/article/details/77894863 二叉树中采用递归方式求解问题。
solution:

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) 
    {
       if(!nums.size()) return NULL;
       int mid = nums.size()/2;
       TreeNode *node=new TreeNode(nums[mid]);
       vector<int> leftnode = vector<int>(nums.begin(),nums.begin()+mid);
       vector<int> rightnode = vector<int>(nums.begin()+mid+1,nums.end());
       if(mid != 0)
           node->left = sortedArrayToBST(leftnode);
        if(mid != nums.size()-1)
            node->right = sortedArrayToBST(rightnode);
        return node;
    }
};
相关标签: tree