其他分享
首页 > 其他分享> > LeetCode 108 Convert Sorted Array to Binary Search Tree DFS

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;
    }
};

标签:Binary,Convert,right,TreeNode,nums,Tree,vector,root,left
来源: https://www.cnblogs.com/xinyu04/p/16530929.html