码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Convert Sorted List to Binary Search Tree

时间:2015-01-11 14:46:32      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

【leetcode】Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4216420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!