• [LeetCode] 108. Convert Sorted Array to Binary Search Tree


    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* sortedArrayToBST(vector<int>& nums) {
            return arrayToBST(0,nums.size()-1,nums);
        }
        TreeNode* arrayToBST(int left,int right,vector<int>& nums){
            if(left>right)return NULL;
            
            int mid=left+(right-left)/2;
            TreeNode* root= new TreeNode(nums[mid]);
            root->left=arrayToBST(left,mid-1,nums);
            root->right=arrayToBST(mid+1,right,nums);
            return root;
        }
    };


  • 相关阅读:
    关系型数据库性能优化总结(转载)
    分区视图(转载)
    硬盘Raid
    AutoFac
    OSI各层的功能和主要协议(转载)
    Squid
    Nginx+Windows负载均衡(转载)
    Mysql命令alter add:增加表的字段
    Delphi调用WebService(通过SoapHeader认证)经验总结
    Delphi开发OCX详细步骤总结
  • 原文地址:https://www.cnblogs.com/cff2121/p/10933162.html
Copyright © 2020-2023  润新知