[LeetCode]108.Convert Sorted Array to Binary Search Tree

【题目】

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

【分析】

二分法,以中间元素i为根节点[start,i-1]递归构建左子树,[i+1,end]递归构建右子树

【代码】

/*********************************
*   日期:2014-12-28
*   作者:SJF0115
*   题目: 108.Convert Sorted Array to Binary Search Tree
*   来源:https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <queue>
#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:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.size() == 0){
            return NULL;
        }//if
        return SortedArrayToBST(num,0,num.size()-1);
    }
private:
    TreeNode* SortedArrayToBST(vector<int> &num,int start,int end){
        if(start > end){
            return NULL;
        }//if
        int mid = (start + end) / 2;
        // 根节点
        TreeNode *root = new TreeNode(num[mid]);
        // 左子树
        TreeNode *leftSubTree = SortedArrayToBST(num,start,mid-1);
        // 右子树
        TreeNode *rightSubTree = SortedArrayToBST(num,mid+1,end);
        // 连接
        root->left = leftSubTree;
        root->right = rightSubTree;
        return root;
    }
};
// 层次遍历
vector<vector<int> > LevelOrder(TreeNode *root) {
    vector<int> level;
    vector<vector<int> > levels;
    if(root == NULL){
        return levels;
    }
    queue<TreeNode*> cur,next;
    //入队列
    cur.push(root);
    // 层次遍历
    while(!cur.empty()){
        //当前层遍历
        while(!cur.empty()){
            TreeNode *p = cur.front();
            cur.pop();
            level.push_back(p->val);
            // next保存下一层节点
            //左子树
            if(p->left){
                next.push(p->left);
            }
            //右子树
            if(p->right){
                next.push(p->right);
            }
        }
        levels.push_back(level);
        level.clear();
        swap(next,cur);
    }//while
    return levels;
}

int main() {
    Solution solution;
    vector<int> num = {1,3,5,6,7,13,20};
    TreeNode* root = solution.sortedArrayToBST(num);
    vector<vector<int> > levels = LevelOrder(root);
    for(int i = 0;i < levels.size();i++){
        for(int j = 0;j < levels[i].size();j++){
            cout<<levels[i][j]<<" ";
        }
        cout<<endl;
    }
}

【错解】

class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num) {
        if(num.size() == 0){
            return NULL;
        }//if
        return SortedArrayToBST(num,0,num.size()-1);
    }
private:
    TreeNode* SortedArrayToBST(vector<int> num,int start,int end){
        int len = end - start;
        if(len < 0){
            return NULL;
        }//if
        int mid = (start + end) / 2;
        // 根节点
        TreeNode *root = new TreeNode(num[mid]);
        // 左子树
        TreeNode *leftSubTree = SortedArrayToBST(num,start,mid-1);
        // 右子树
        TreeNode *rightSubTree = SortedArrayToBST(num,mid+1,end);
        // 连接
        root->left = leftSubTree;
        root->right = rightSubTree;
        return root;
    }
};

解析:

注意到这一句代码:TreeNode* SortedArrayToBST(vector<int> num,int start,int end)

传递num是值传递,不是引用传递,所以每次递归调用SortedArrayToBST函数时,它会再次复制这个大vector。所以在递归过程中,这种行为将花费很大内存。

时间: 2024-10-23 15:59:14

[LeetCode]108.Convert Sorted Array to Binary Search Tree的相关文章

[LeetCode]109.Convert Sorted List to Binary Search Tree

[题目] Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. [分析] 无 [代码] 在下面超时的代码上进行改进:把链表先转换为vector再进行操作. [LeetCode]108.Convert Sorted Array to Binary Search Tree /*******************************

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树的创建过程实现了一遍,记录一下: C++实现代码: #include<iostream> #include<new> #include<vector> #include<cmath> u

[LeetCode]235.Lowest Common Ancestor of a Binary Search Tree

题目 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes v and w as the lowest node in T that h

[LeetCode]173.Binary Search Tree Iterator

[题目] Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and

[LeetCode]99.Recover Binary Search Tree

[题目] Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? [解析] O(n) 空间的解法是,开一个指针数组

[LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary

Geeks 面试题之Optimal Binary Search Tree

Dynamic Programming | Set 24 (Optimal Binary Search Tree) Given a sorted array keys[0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches to keys[i]. Construct a binary search tree of all keys

二叉查找树(binary search tree)详解

二叉查找树(Binary Search Tree),也称二叉排序树(binary sorted tree),是指一棵空树或者具有下列性质的二叉树: 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值 任意节点的左.右子树也分别为二叉查找树 没有键值相等的节点(no duplicate nodes) 本文地址:http://www.cnblogs.com/archimedes/p/binary-search-tree

算法:uva-10304 Optimal Binary Search Tree(区间dp)

题意 给一个序列即可 S = (e1,e2,...,en),且e1<e2<..<en.要把这些序列构成一个二叉搜索 树. 二叉搜索树是具有递归性质的,且若它的左子树不空,则左子树上所有结点的值均小于它的根结点的 值: 若它 的右子树不空,则右子树上所有结点的值均大于它的根结点的值. 因为在实际应用中,被访 问频率越高的元素,就应该越接近根节点,这样才能更加节省查找时间. 每个元素有一个访问频率f(ei) ,当元素位于深度为k的地方,那么花费cost(ei) = k. 所有节点的花费和访问