【leetcode】Convert Sorted List to Binary Search Tree

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)
 
 1 /**

 2  * Definition for singly-linked list.

 3  * struct ListNode {

 4  *     int val;

 5  *     ListNode *next;

 6  *     ListNode(int x) : val(x), next(NULL) {}

 7  * };

 8  */

 9 /**

10  * Definition for binary tree

11  * struct TreeNode {

12  *     int val;

13  *     TreeNode *left;

14  *     TreeNode *right;

15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

16  * };

17  */

18 class Solution {

19 public:

20     TreeNode *sortedListToBST(ListNode *head) {

21        

22         ListNode *p=head;

23         int len=0;

24         while(p!=NULL)

25         {

26             p=p->next;

27             len++;

28         }

29        

30         TreeNode * root=buildTree(head,0,len-1);

31         return root;

32        

33     }

34    

35    

36     TreeNode *buildTree(ListNode *&node,int left,int right)

37     {

38         if(left>right) return NULL;

39        

40         int mid=(left+right)/2;

41        

42         TreeNode *leftTree=buildTree(node,left,mid-1);

43         TreeNode *root=new TreeNode(node->val);

44         node=node->next;

45         TreeNode *rightTree=buildTree(node,mid+1,right);

46         root->left=leftTree;

47         root->right=rightTree;

48         return root;

49     }

50    

51 };

 

你可能感兴趣的:(Binary search)