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

      

    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7507307.html
Copyright © 2011-2022 走看看