Convert Sorted Array to Binary Search Tree

简介: Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 首先我是要AVL树的创建过程进行操作,不过提交之后出现超时,但还是让我将AVL树的创建过程实现了一遍,...

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

首先我是要AVL树的创建过程进行操作,不过提交之后出现超时,但还是让我将AVL树的创建过程实现了一遍,记录一下:

C++实现代码:

#include<iostream>
#include<new>
#include<vector>
#include<cmath>
using namespace std;

//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 *sortedArrayToBST(vector<int> &num)
    {
        if(num.empty())
            return NULL;
        TreeNode *root=NULL;
        int i;
        for(i=0; i<(int)num.size(); i++)
            insert(root,num[i]);
        return root;
    }
    void insert(TreeNode *&root,int key)
    {int lhigh,rhigh;
        if(root==NULL)
        {
            root=new TreeNode(key);
            if(root==NULL)
                return;
        }
        else if(key<root->val)
        {
            insert(root->left,key);
            lhigh=maxDepth(root->left);
            rhigh=maxDepth(root->right);
            if(abs(lhigh-rhigh)>1)
            {
                if(key<root->left->val)
                    SingleRotateWithLeft(root);
                else
                    DoubleRotateWithLeft(root);
            }
        }
        else
        {
            insert(root->right,key);
            lhigh=maxDepth(root->left);
            rhigh=maxDepth(root->right);
            if(abs(lhigh-rhigh)>1)
            {
                if(key>root->right->val)
                    SingleRotateWithRight(root);
                else
                    DoubleRotateWithLeft(root);
            }
        }
    }
    int maxDepth(TreeNode *root)
    {
        if(root)
        {
            if(root->left==NULL&&root->right==NULL)
                return 1;
            int leftDepth=maxDepth(root->left);
            int rightDepth=maxDepth(root->right);
            return leftDepth>= rightDepth ?(leftDepth+1):(rightDepth+1);
        }
        return 0;
    }
    void SingleRotateWithLeft(TreeNode *&root)
    {
        TreeNode *l=root->left;
        root->left=l->right;
        l->right=root;
        root=l;
    }
    void SingleRotateWithRight(TreeNode *&root)
    {
        TreeNode *r=root->right;
        root->right=r->left;
        r->left=root;
        root=r;
    }
    void DoubleRotateWithLeft(TreeNode *&root)
    {
        SingleRotateWithRight(root->left);
        SingleRotateWithLeft(root);
    }
    void DoubleRotateWithRight(TreeNode *&root)
    {
        SingleRotateWithLeft(root->right);
        SingleRotateWithRight(root);
    }
    void inorder(TreeNode *root)
    {
        if(root)
        {
            inorder(root->left);
            cout<<root->val<<" ";
            inorder(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode *root=NULL;
    vector<int> vec={1,2,3,4,5,6,7,8,9,10};
    root=s.sortedArrayToBST(vec);
    s.inorder(root);
    cout<<endl;
    cout<<s.maxDepth(root)<<endl;
}

运行结果:

 

提交的代码:

#include<iostream>
#include<new>
#include<vector>
#include<cmath>
using namespace std;

//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 *sortedArrayToBST(vector<int> &num)
    {
        if(num.empty())
            return NULL;//递归的退出条件,一定要写哦
        TreeNode *root=NULL;
        int left=0;
        int right=num.size()-1;
        int mid=(left+right)/2;
        root=new TreeNode(num[mid]);
        vector<int> l(mid);
        vector<int> r(right-mid);
        int i;
        for(i=0;i<mid;i++)
            l[i]=num[i];
        for(i=mid+1;i<(int)num.size();i++)
            r[i-mid-1]=num[i];
        root->left=sortedArrayToBST(l);
        root->right=sortedArrayToBST(r);
        return root;
    }
    int maxDepth(TreeNode *root)
    {
        if(root)
        {
            if(root->left==NULL&&root->right==NULL)
                return 1;
            int leftDepth=maxDepth(root->left);
            int rightDepth=maxDepth(root->right);
            return leftDepth>= rightDepth ?(leftDepth+1):(rightDepth+1);
        }
        return 0;
    }
    TreeNode* SingleRotateWithLeft(TreeNode *&root)
    {
        TreeNode *l=root->left;
        root->left=l->right;
        l->right=root;
        return l;
    }
    TreeNode* SingleRotateWithRight(TreeNode *&root)
    {
        TreeNode *r=root->right;
        root->right=r->left;
        r->left=root;
        return r;
    }
    TreeNode* DoubleRotateWithLeft(TreeNode *&root)
    {
        SingleRotateWithRight(root->left);
        return SingleRotateWithLeft(root);
    }
    TreeNode* DoubleRotateWithRight(TreeNode *&root)
    {
        SingleRotateWithLeft(root->right);
        return SingleRotateWithRight(root);
    }
    void inorder(TreeNode *root)
    {
        if(root)
        {
            inorder(root->left);
            cout<<root->val<<" ";
            inorder(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode *root=NULL;
    vector<int> vec={1,2,3,4,5,6,7,8,9,10};
    root=s.sortedArrayToBST(vec);
    s.inorder(root);
    cout<<endl;
    cout<<s.maxDepth(root)<<endl;
}

 

相关文章
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
119 0
|
算法
LeetCode Find Minimum in Rotated Sorted Array II
假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。 注意数组中可能存在重复的元素。
136 0
LeetCode Find Minimum in Rotated Sorted Array II
LeetCode 153. Find Minimum in Rotated Sorted Array
假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 请找出其中最小的元素。 你可以假设数组中不存在重复元素。
148 0
LeetCode 153. Find Minimum in Rotated Sorted Array
LeetCode 108. Convert Sorted Array to BST
给定一个数组,其中元素按升序排序,将其转换为高度平衡的BST。 对于这个问题,高度平衡的二叉树被定义为:二叉树中每个节点的两个子树的深度从不相差超过1。
187 0
LeetCode 108. Convert Sorted Array to BST
LeetCode 88. Merge Sorted Array
题意是给定了两个排好序的数组,让把这两个数组合并,不要使用额外的空间,把第二个数组放到第一个数组之中.
124 0
LeetCode 88. Merge Sorted Array
|
索引
LeetCode 81. Search in Rotated Sorted Array II
假设按升序排序的数组在事先未知的某个枢轴处旋转。 (例如, [0,0,1,2,2,5,6] 可能变成 [2,5,6,0,0,1,2]). 给定一个要搜索的目标值T, 如果该目标值能在数组中找到则返回true,否则返回false。
143 0
LeetCode 81. Search in Rotated Sorted Array II
LeetCode 80 Remove Duplicates from Sorted Array II
给定排序的数组nums,就地删除重复项,使重复项最多出现两次并返回新的长度. 不要为另一个数组分配额外的空间,必须通过使用O(1)复杂度的额外空间来修改输入数组,从而实现此目的.
177 0
LeetCode 80 Remove Duplicates from Sorted Array II
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
159 0
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
135 0
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree

热门文章

最新文章

  • 1
    Java 中数组Array和列表List的转换
    392
  • 2
    JavaScript中通过array.map()实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等,array.map()的使用详解(附实际应用代码)
    452
  • 3
    通过array.reduce()实现数据汇总、条件筛选和映射、对象属性的扁平化、转换数据格式、聚合统计、处理树结构数据和性能优化,reduce()的使用详解(附实际应用代码)
    1032
  • 4
    通过array.some()实现权限检查、表单验证、库存管理、内容审查和数据处理;js数组元素检查的方法,some()的使用详解,array.some与array.every的区别(附实际应用代码)
    290
  • 5
    通过array.every()实现数据验证、权限检查和一致性检查;js数组元素检查的方法,every()的使用详解,array.some与array.every的区别(附实际应用代码)
    171
  • 6
    多维数组操作,不要再用遍历循环foreach了!来试试数组展平的小妙招!array.flat()用法与array.flatMap() 用法及二者差异详解
    115
  • 7
    别再用双层遍历循环来做新旧数组对比,寻找新增元素了!使用array.includes和Set来提升代码可读性
    116
  • 8
    Array.forEach实战详解:简化循环与增强代码可读性;Array.forEach怎么用;面对大量数据时怎么提高Array.forEach的性能
    90
  • 9
    深入理解 JavaScript 中的 Array.find() 方法:原理、性能优势与实用案例详解
    299
  • 10
    JavaScript 中通过Array.sort() 实现多字段排序、排序稳定性、随机排序洗牌算法、优化排序性能,JS中排序算法的使用详解(附实际应用代码)
    554