zoukankan      html  css  js  c++  java
  • [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;
        }
    };


  • 相关阅读:
    IP地址加时间戳加3位随机数
    你会想造一艘船吗?
    提问的智慧
    建造者模式
    设计模式(一)
    jeesite中activiti中的流程表梳理
    如何读书、学习?
    zxing生成高容错率二维码,以及添加文字
    LVM磁盘划分
    阿里云盘扩容(SUSE Linux下)
  • 原文地址:https://www.cnblogs.com/cff2121/p/10933162.html
Copyright © 2011-2022 走看看