【leetcode】Convert Sorted List to Binary Search Tree

时间:2023-12-16 18:09:56

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.

可以采用类似于Covert Sorted Array to Binary Search Tree的方法,但是寻找中点对于链表来说效率较低
可以采用更高效的递归方式,无需寻找中点
注意引用传递:TreeNode *buildTree(ListNode *&node,int left,int right)
 /**
* 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) { ListNode *p=head;
int len=;
while(p!=NULL)
{
p=p->next;
len++;
} TreeNode * root=buildTree(head,,len-);
return root; } TreeNode *buildTree(ListNode *&node,int left,int right)
{
if(left>right) return NULL; int mid=(left+right)/; TreeNode *leftTree=buildTree(node,left,mid-);
TreeNode *root=new TreeNode(node->val);
node=node->next;
TreeNode *rightTree=buildTree(node,mid+,right);
root->left=leftTree;
root->right=rightTree;
return root;
} };