码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Convert Sorted Array to Binary Search Tree

时间:2014-06-21 00:47:08      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   tar   color   

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.

 

 

 

 

[LeetCode] Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

[LeetCode] Convert Sorted Array to Binary Search Tree

标签:style   class   blog   code   tar   color   

原文地址:http://www.cnblogs.com/Xylophone/p/3795572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!