Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
要点就是找到中心点,然后分别递归构造左边的数和右边的数
TreeNode* sortedArrayToBST(vector<int>& nums, int beg, int end) { if (beg > end) return nullptr; int mid = (beg + end) >> 1; TreeNode* root = new TreeNode(nums[mid]); root->left = sortedArrayToBST(nums, beg, mid - 1); root->right = sortedArrayToBST(nums, mid + 1, end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { return sortedArrayToBST(nums, 0, nums.size()-1); }
链表为了代码的简洁,我使用了二级指针,不过可读性变差了
TreeNode* sortedListToBST(ListNode* head) { if (head == nullptr) return nullptr; ListNode* fast = head; ListNode** slow = &head; while (fast->next != nullptr && fast->next->next != nullptr) { fast = fast->next->next; slow = &((*slow)->next); } TreeNode* root = new TreeNode((*slow)->val); root->right = sortedListToBST((*slow)->next); *slow = nullptr; root->left = sortedListToBST(head); return root; }
以上是关于Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
108. Convert Sorted Array to Binary Search Tree
Convert Sorted Array to Binary Search Tree
leetcode 108 Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree