zoukankan      html  css  js  c++  java
  • Convert Sorted Array to Binary Search Tree 分类: Leetcode 2014-12-07 10:49 74人阅读 评论(0) 收藏

    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 *create(vector<int> &num,int begin,int end)
        {
            if(begin>end) return NULL;
            int mid;
            mid=(end+begin)/2;
            
            TreeNode *leftNode=create(num,begin,mid-1);
            TreeNode *rightNode=create(num,mid+1,end);
            
            TreeNode *node = new TreeNode(num[mid]);
            
            node->left=leftNode;
            node->right=rightNode;
            
            return node;
        }
        
        TreeNode *sortedArrayToBST(vector<int> &num) {
            return create(num,0,num.size()-1);
            
        }
        
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    objc之method&class attributes
    iOS之Export UIAutomation script
    js's forin vs oc's forin
    iOS新加速计事件
    Mac之Font管理
    iOS之VoiceOver
    OC之initialize
    C++常见问题
    objc新老runtime接口类型对比
    dlopen之mode参数详解
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656983.html
Copyright © 2011-2022 走看看