• LeetCode OJ——Convert Sorted Array to Binary Search Tree


    http://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

    将一个升序的数组转换成 height balanced BST高度平衡的二叉搜索树,根据二叉搜索树的特征,所有比根节点小的值,都在根节点的左边,所有比根节点大的值,都在根节点的右边。建立的过程就是一个个的插入。但要求是高度平衡的,即不能是各种偏的那样,否则的话,搜索的代价会增大,最佳的时候是O(height),height balanced的时候也是O(height).所以会涉及到各种左旋转,右旋转,先左旋再右旋,先右旋再左旋的操作(为了平衡高度),即AVL树。

    但是根据本题的特点,数组是有序的,所以可以找到最佳高度的构造,只要一直去中点来做根,递归建造。代码如下:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    struct TreeNode {
        int val;
        TreeNode *left;
         TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     };
    
    class Solution {
    public:
        void fun(int i,int j,TreeNode *node,vector<int> &num)
        {
            if(i==j)
            {
                node->val = num[i];
                return;
            }
            int mid = (j-i)/2+i;
            node->val = num[mid];
            if(mid-1>=i)
            {
                TreeNode *nodeLeft = new TreeNode(0);
                node->left = nodeLeft;
                fun(i,mid-1,nodeLeft,num);
            }
            if(j>=mid+1)
            {            
                TreeNode *nodeRight = new TreeNode(0);
                node->right = nodeRight;
                fun(mid+1,j,nodeRight,num);
            }
            
        }
        TreeNode *sortedArrayToBST(vector<int> &num) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(num.size()==0)
                return NULL;
            
            TreeNode *root = new TreeNode(0);
            fun(0,num.size()-1,root,num);
    
            return root;        
        }
    };
    
    int main()
    {
        Solution *mySolution = new Solution();
        vector<int> input;
        //input.push_back(1);
        //input.push_back(3);
        //input.push_back(5);
        //input.push_back(7);
        //input.push_back(9);
        mySolution->sortedArrayToBST(input);
        
        return 0;
    }
  • 相关阅读:
    LeetCode: 18. 4Sum
    LeetCode:15. 3Sum
    Leetcode:1. Two Sum
    tensorflow placeholder
    Tensorflow变量
    13.git的简单使用
    13.Django1.11.6文档
    12.python进程协程异步IO
    12.Flask-Restful
    12.Django思维导图
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3435762.html
Copyright © 2020-2023  润新知