玩命加载中 . . .

108/109-数组转为二叉搜索树


LeetCode 108. Convert Sorted Array to Binary Search Tree

LeetCode-108

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5] or [0,-10,5,null,-3,null,9]

Explanation:

method

数组中间节点为根节点,递归处理左边数组和右边数组
注意还是左闭右开[begin, end)

TreeNode* traversal(vector<int>& nums, int begin, int end) {
    if (begin >= end) return nullptr;
    int mid = begin + end >> 1;
    TreeNode *root = new TreeNode(nums[mid]);
    root->left = traversal(nums, begin, mid);
    root->right = traversal(nums, mid + 1, end);
    return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
    return traversal(nums, 0, nums.size());
}


LeetCode 109. Convert Sorted List to Binary Search Tree

LeetCode-109

Given the head of a singly linked list 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 1:

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

method

跟数组一样维护一个左闭右开的区间[head, tail),然后找中间节点

TreeNode* traversal(ListNode *head, ListNode *tail) {
    if (head == tail) return nullptr;   // 空节点
    ListNode *fast = head;
    ListNode *slow = head;
    while (fast != tail && fast->next != tail) {    // 注意这里是tail
        fast = fast->next->next;
        slow = slow->next;
    }
    TreeNode *root = new TreeNode(slow->val);
    root->left = traversal(head, slow);
    root->right = traversal(slow->next, tail);
    return root;
}
TreeNode* sortedListToBST(ListNode* head) {
    return traversal(head, nullptr);
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录