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.

https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/點擊打開鏈接

問題分析:

num[start, end] 有序數組轉換成平衡BST

1. 取出數組中間元素將數組劃分成相等的兩部分。

2. num[start, mid - 1]中是左子樹, num[mid + 1, end] 中是右子樹,num[mid] 是根。

3. 以上過程遞歸構造各自子樹。

示例代碼:

    TreeNode *sortedAarrytoTree(vector<int> &num, int start, int end)
    {
        if (start > end) return NULL;
        int cur = (start + end) / 2;
        TreeNode *root = new TreeNode(num[cur]);
        root->left = sortedAarrytoTree(num, start, cur - 1);
        root->right = sortedAarrytoTree(num, cur + 1, end);
        return root;
    }


發佈了149 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章