zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】树题17:Convert Sorted Array to Binary Search Tree

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    Convert Sorted Array to Binary Search Tree

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.
    Example:
    Given the sorted array: [-10,-3,0,5,9],
     
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
     
       0
      / 
     -3   9
     /    /
    -10  5

    C++
     
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     
    /*
    方法:分治法(分成处理左右子序列的问题,与快速排序写法类似)
    二叉查找树,根结点总是大于左子树所有结点值,小于右子树所有结点值,中序遍历序列为升序排列
     
    分析:转化成一个height-balanced的二叉查找树所以数组中点就是二叉查找树的根结点
    写递归思路:先写递归的主体,再写起点输入,再写递归的出口return语句(尤其注意递归的子函数的出口)
    */
    class Solution
    {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums)
        {
            return buildTree(nums,0,nums.size()-1); //注意索引从0开始
        }
       
        TreeNode* buildTree(vector<int>& nums, int start, int end)
        {
           
            if(start > end) return NULL; //递归子函数的出口(不能取等号,因为单个元素也要分配空间)
           
            int mid = (start + end + 1)/2; //+1是为了向上取整,由于是升序排列,当(start+end)/2不为整数时,取较大的那个数作为根
            TreeNode* root = new TreeNode(nums[mid]);   //构建根结点
            root->left = buildTree(nums, start, mid-1); //构建左子树
            root->right = buildTree(nums, mid+1, end); //构建右子树
           
            return root; //递归原始母函数的出口,返回最顶层的根结点指针
           
        }
    };
     
  • 相关阅读:
    self 和 super 关键字
    NSString类
    函数和对象方法的区别
    求两个数是否互质及最大公约数
    TJU Problem 1644 Reverse Text
    TJU Problem 2520 Quicksum
    TJU Problem 2101 Bullseye
    TJU Problem 2548 Celebrity jeopardy
    poj 2586 Y2K Accounting Bug
    poj 2109 Power of Cryptography
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225853.html
Copyright © 2011-2022 走看看