LeetCode | Convert Sorted Array to Binary Search Tree

题目:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.


思路:

自顶向下地构造平衡二叉树。

代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(num.size() == 0)
        {
            return NULL;
        }
        return sortedArrayToBST(num, 0, num.size()-1);
    }
    
    TreeNode *sortedArrayToBST(vector<int> &num, int begin, int end) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(begin>end)
        {
            return NULL;
        }
        else
        {
            int mid = begin + ((end - begin)>>1);
            
            TreeNode* parent = new TreeNode(num[mid]);
            parent->left = sortedArrayToBST(num, begin, mid-1);
            parent->right = sortedArrayToBST(num, mid+1, end);
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11898523
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞