LeetCode 0108 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

题意

有序数组转化为二叉搜索树

思路1

  • 始终选择中间位置左边元素作为根节点然后分别构造左右子树

代码1

/**
 * 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 {
private:
    vector<int> nums;
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        this->nums = nums;
        return helper(0, nums.size() - 1);
    }
    
    TreeNode* helper(int left, int right){
        if(left > right) return NULL;
        // 始终选择中间位置左边元素作为根节点
        int p = (left + right) / 2;
        TreeNode *root = new TreeNode(nums[p]);
        root->left = helper(left, p - 1);
        root->right = helper(p + 1, right);
        return root;
    }
};
原创文章 193 获赞 27 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/105737125
今日推荐