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 binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode *build(vector<int>&num,int start,int end) {
            if(start>=end) {
                return NULL;
            }
            int mid=start+(end-start)/2;
            TreeNode *node=new TreeNode(num[mid]);
            node->left=build(num,start,mid);
            node->right=build(num,mid+1,end);
        	return node;
        }
        
        TreeNode *sortedArrayToBST(vector<int> &num) {
            if(num.size()==0)	return NULL;
            return build(num,0,num.size());
        }
        
    };
    

      

    class Solution {
    public:
        TreeNode *constructtree(vector<int> &num,int begin,int end){
            if(begin>end) return nullptr;
            int mid=(begin+end+1)/2;
            TreeNode *root=new TreeNode(num[mid]);
            if(begin<mid){
            root->left=constructtree(num,begin,mid-1);
            root->right=constructtree(num,mid+1,end);
            }
            return root;
        }
        TreeNode *sortedArrayToBST(vector<int> &num) {
            if(num.size()==0) return nullptr;
            return constructtree(num,0,num.size()-1);
        }
    };
    

      

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    服务器出现大量的127.0.0.1:3306 TIME_WAIT连接 解决方法 [转载]
    phpize安装php扩展CURL
    linux位数查看
    Linux下Sublime Text 3的安装
    ECstore后台报表显示空白问题解决办法
    centos 上安装phpstorm
    Nginx禁止目录执行php文件权限
    vue 动画
    vue的路由
    组件的传值 组件之间的通讯
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7507307.html
Copyright © 2011-2022 走看看