108. Convert Sorted Array to Binary Search Tree & 109. Convert Sorted List to Binary Search Tree
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
Analysis
这两道题内容类似,区别就是108要将数组形式的一串数字构成BST,而109用的是链表形式的数字。而BST是任何一个节点的左右两子树的高度的差不大于1,且任意节点的左子树上所有节点的值都比它小,右子树上所有节点的值都比它大。
其解题目标都是要在已排好序的一串数字中,找到排在中间位置的数字,作为根节点,然后如二分法般,递归地在以该根节点为中心的左右两子串的数字中再找到中间的节点,作为左右两子树的根。
而108中,要想找到数组形式的数字的中间值,可根据下标来查找;109中,在链表中找到中间值,则需要利用快慢指针的技巧。即设置一个“快指针”fast,和一个“慢指针”slow。其中fast每次向后走两步,即fast = fast->next->next;而slow每次只走一步,即slow = slow->next。当fast到达链表的最后一个节点时(fast->next == NULL),slow即为中间节点。
Code
以下为108题(Array)的代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0)
return NULL;
TreeNode* root = NULL;
root = helper(nums, 0, nums.size()-1);
return root;
}
TreeNode* helper(vector<int>& nums, int low, int high){
if(low>high)
return NULL;
int mid = low+(high-low)/2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = helper(nums, low, mid-1);
node->right = helper(nums, mid+1, high);
return node;
}
};
以下为109题(List)的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
return NULL;
TreeNode* res = helper(head, NULL);
return res;
}
TreeNode* helper(ListNode* head, ListNode* tail){
if(head == tail)
return NULL;
ListNode* fast = head;
ListNode* slow = head;
while(fast!=tail && fast->next!=tail){
fast = fast->next->next;
slow = slow->next;
}
TreeNode* node = new TreeNode(slow->val);
node->left = helper(head, slow);
node->right = helper(slow->next, tail);
return node;
}
};