zoukankan      html  css  js  c++  java
  • 108. Convert Sorted Array to Binary Search Tree

    Description:

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example:

    Given the sorted array: [-10,-3,0,5,9],
    
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
    
          0
         / 
       -3   9
       /   /
     -10  5

    class Solution {
    public:
        TreeNode* sortedArrayToBSTCore(vector<int>& nums, int left, int right)
     {
         if(left>right)
            return NULL;
         TreeNode* root=new TreeNode(0);
         int core=(right+left+1)/2;
         root->val=nums[core];
         root->left=sortedArrayToBSTCore(nums,left,core-1);
         root->right=sortedArrayToBSTCore(nums,core+1,right);
         return root;
     }
     TreeNode* sortedArrayToBST(vector<int>& nums) {
            
           int begin=0;
           int end=nums.size()-1;
           return sortedArrayToBSTCore(nums,begin,end);
        }
    };
  • 相关阅读:
    JNUOJ 1187
    JNUOJ 1184
    HDU 4848
    HDU 4849
    哈夫曼树和哈弗曼编码小记
    HDU 5726
    POJ 3368 & UVA 11235
    2016江苏省CPC省赛 I
    POJ 3928
    POJ 3067
  • 原文地址:https://www.cnblogs.com/zhaoyaxing/p/8488799.html
Copyright © 2011-2022 走看看