zoukankan      html  css  js  c++  java
  • [LeetCode] Convert Sorted Array to Binary Search Tree

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

    说明:平衡二叉搜索树,即任何结点的左子树和右子树高度最多相差1的二叉搜索树。

    二叉搜索树二叉查找树(Binary Search Tree),或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树

    编程思想:取中间值作为根节点,再取前一半的中间值作为左子树根节点,取后一半的中间值作为右子树的根节点,迭代直到叶子结点。

    以下编程用递归的方法,LeetCode提示:Memory Limit Exceeded,把调用的函数CreatNode(vector<int> num,int start,int end)

    改成CreatNode(vector<int> &num,int start,int end)就好了。即:传递vector形参,用其引用,在不断递归调用中可以大大节省空间,则每次调用都要复制一个vector的副本,很浪费空间的!!!

    /**
     * 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) {
            int len = num.size();
            return CreatNode(num,0,len-1);
        }
    private:
        TreeNode *CreatNode(vector<int> num,int start,int end){
    //改为TreeNode *CreatNode(vector<int> &num,int start,int end)就不会出现Memory Limit Exceeded的错误啦!!!!!!!!!! if(end<start) return NULL; TreeNode *p = new TreeNode(0); int middle = (start+end+1)/2;//必须要加上1,否则num为偶数个时取不上中值 p->val = num[middle]; p->left = CreatNode(num,start,middle-1); p->right = CreatNode(num,middle+1,end); return p; } };

    多么痛的领悟:Pay attention to this statement TreeNode *CreatNode(vector<int>num,int start,int end). I pass num by value, not by reference, so every time it call the function CreatNode, it will copy the big vector one more time. So in your recursion process, this behavior will cost large memory.

  • 相关阅读:
    相关分析[SDOI2017]
    排序[HEOI2016/TJOI2016]
    逆序对[AHOI2008]
    逆序对数列[HAOI2009]
    小Z的袜子「2009国家集训队」
    http抓包—Content-Type讲解
    mysql——leetcode问题记录
    linux--vi命令
    Linux—echo命令
    Linux—文件命令之touch命令
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3795572.html
Copyright © 2011-2022 走看看