【LeetCode】108. Convert Sorted Array to Binary Search Tree(C++)

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

这道题弄了好久,就是因为结果的树是有点反的,在网上找了许多程序,结果都是这样。最后提交一下试试竟然过了,让我这个小白很慌。。。

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



猜你喜欢

转载自blog.csdn.net/biongbiongdou/article/details/80316121