xinyu04

导航

LeetCode 108 Convert Sorted Array to Binary Search Tree DFS

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Solution

选取每个序列的中间节点作为 \(root\) ,然后根据 \(root\) 划分左右子数,按照相同的方式来求解

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size()==0) return NULL;
        if(nums.size()==1) return new TreeNode(nums[0]);
        
        int mid = nums.size()/2;
        TreeNode* root = new TreeNode(nums[mid]);
        
        vector<int> left_nums = vector<int>(nums.begin(), nums.begin()+mid);
        vector<int> right_nums = vector<int>(nums.begin()+mid+1, nums.end());
        
        root->left = sortedArrayToBST(left_nums);
        root->right = sortedArrayToBST(right_nums);
        return root;
    }
};

posted on 2022-07-29 05:59  Blackzxy  阅读(11)  评论(0编辑  收藏  举报