频道栏目
首页 > 资讯 > C++ > 正文

leetcode Convert Sorted List to Binary Search Tree

13-10-17        来源:[db:作者]  
收藏   我要投稿
The problem is quite interesting when limiting memory to O(1), and time complexity to O(n). In that way, extra array is forbidden. So
 
When there is only one node A, mid = A, NULL<-mid->NULL
 
When there are two node A, A+1, mid = A, NULL<-mid->A+1
 
When there are three node A, A+1, A+2, mid = A+1, A<-A+1->A+2
 
....
 
After building the tree, the pointer moves to the end. The code is like: 
 
 
/** 
 * 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* BuildTree(ListNode*& head, int start, int end) {  
      if (start > end)   
        return NULL;  
      int mid = start + (end - start) / 2;  
        
      TreeNode* lChild = BuildTree(head, start, mid - 1);  
      TreeNode* parent = new TreeNode(head->val);  
      parent->left = lChild;  
      head = head->next;  
      TreeNode* rChild = BuildTree(head, mid + 1, end);  
      parent->right = rChild;  
      return parent;  
  }  
  TreeNode *sortedListToBST(ListNode *head) {  
    // Note: The Solution object is instantiated only once and is reused by each test case.  
    ListNode* p = head;  
    int len = 0;   
    while (p != NULL) {  
        len++;  
        p = p->next;  
    }  
    return BuildTree(head, 0, len-1);  
  }  
};  

 

 
 
I once wrote the function like:
 
TreeNode* BuildTree(ListNode* head, int start, int end)  
which got wrong answer. 

 


相关TAG标签
上一篇:windows蓝屏日志文件、dump文件收集方法
下一篇:手机病毒的入侵和防御
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站