Convert Sorted List to Binary Search Tree——将链表转换为平衡二叉搜索树 &&convert-sorted-array-to-binary-search-tree——将数列转换为bst

时间:2023-03-09 05:26:10
Convert Sorted List to Binary Search Tree——将链表转换为平衡二叉搜索树  &&convert-sorted-array-to-binary-search-tree——将数列转换为bst

Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

为了满足平衡要求,容易想到提出中间节点作为树根,因为已排序,所以左右两侧天然满足BST的要求。

左右子串分别递归下去,上层根节点连接下层根节点即可完成。

递归找中点,然后断开前后两段链表,并继续找中点

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* 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;
if(head->next==NULL) return new TreeNode(head->val);
ListNode *mid=findMid(head);
TreeNode *root=new TreeNode(mid->val);
root->left=sortedListToBST(head);
root->right=sortedListToBST(mid->next);
return root;
}
ListNode *findMid(ListNode *root){
if(root==NULL) return NULL;
if(root->next==NULL) return root;
ListNode *fast,*slow,*pre;
fast=root;
slow=root;
while(fast!=NULL){
fast=fast->next;
if(fast!=NULL){
fast=fast->next;
pre=slow;
slow=slow->next;
}
}
pre->next=NULL;
return slow;
}
};

convert-sorted-array-to-binary-search-tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
int n=num.size();
if(n<) return NULL; return findMid(num,,n-);
}
TreeNode *findMid(vector<int> &num, int l,int r){
if(l>r) return NULL;
int mid=(l+r+)/;
TreeNode *root=new TreeNode(num[mid]);
root->left=findMid(num,l,mid-);
root->right=findMid(num,mid+,r);
return root;
}
};