zoukankan      html  css  js  c++  java
  • 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 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) {
            if (nums.empty())
                return nullptr;
            TreeNode *root = helper(nums, 0, nums.size()-1);
            return root;
        }
        TreeNode *helper(vector<int>& nums, int start, int end){
            if (start > end)
                return nullptr;
            int mid = start + (end - start)/2;
            TreeNode *root = new TreeNode(nums[mid]); #指针new
            root->left = helper(nums, start, mid-1);
            root->right = helper(nums, mid+1, end);
            return root;
        }
    };
  • 相关阅读:
    Web应用网络模型
    Http协议
    Array数组标准库
    Array数组基础
    javascript--Object
    javascript--Function
    letCode-3
    面试前的准备
    面试常见问题
    面试经验总结
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5822817.html
Copyright © 2011-2022 走看看