[Leetcode] Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree 题解

题目来源:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/


Description

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 every node 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

Solution

class Solution {
private:
    struct Task {
        TreeNode **nodep;
        int start, end;
        Task(TreeNode **p, int s, int e) :
                nodep(p), start(s), end(e) {}
    };
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if (nums.empty())
            return NULL;
        TreeNode *root, *node;
        int start, end, mid;
        queue<Task> q;
        q.push(Task(&root, 0, nums.size() - 1));
        while (!q.empty()) {
            Task task = q.front();
            q.pop();
            start = task.start;
            end = task.end;
            if (start > end)
                continue;
            mid = (start + end) / 2;
            node = new TreeNode(nums[mid]);
            *(task.nodep) = node;
            if (start == end)
                continue;
            q.push(Task(&(node -> left), start, mid - 1));
            q.push(Task(&(node -> right), mid + 1, end));
        }
        return root;
    }
};


解题描述

这道题题意是,将一个有序数组转换成一个BST(二分查找树),并且要求输出的BST是一棵平衡树(每个节点的左右子树高度差小于1)。解法上我用的是迭代,每次都将数组的最中间数据作为当前子树的根节点,左边的数据作为左子树,右边的数据作为右子树,将左右范围加入任务队列,循环出入队即可完成建树。这里是通过每次从中间分开左右子树来保证整棵树的平衡性。

posted @ 2018-02-01 16:03  言何午  阅读(112)  评论(0编辑  收藏  举报