博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Convert Sorted List to Binary Search Tree, Solution
阅读量:6614 次
发布时间:2019-06-24

本文共 1688 字,大约阅读时间需要 5 分钟。

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
[Thoughts]
It is similar with "
Convert Sorted Array to Binary Search Tree". But the difference here is we have no way to random access item in O(1).
If we build BST from array, we can build it from top to bottom, like
1. choose the middle one as root,
2. build left sub BST
3. build right sub BST
4. do this recursively.
But for linked list, we can't do that because Top-To-Bottom are heavily relied on the index operation.
There is a smart solution to provide an Bottom-TO-Top as an alternative way, 
With this, we can insert nodes following the list’s order. So, we no longer need to find the middle element, as we are able to traverse the list while inserting nodes to the tree.
[Code]
1:    TreeNode *sortedListToBST(ListNode *head) {  2:      // Start typing your C/C++ solution below  3:      // DO NOT write int main() function  4:      int len =0;  5:      ListNode *p = head;  6:      while(p)  7:      {  8:        len++;  9:        p = p->next;  10:      }  11:      return BuildBST(head, 0, len-1);  12:    }  13:    TreeNode* BuildBST(ListNode*& list, int start, int end)  14:    {  15:      if (start > end) return NULL;  16:      int mid = (start+end)/2;   //if use start + (end - start) >> 1, test case will break, strange! 17:      TreeNode *leftChild = BuildBST(list, start, mid-1);  18:      TreeNode *parent = new TreeNode(list->val);  19:      parent->left = leftChild;  20:      list = list->next;  21:      parent->right = BuildBST(list, mid+1, end);  22:      return parent;  23:    }

转载于:https://www.cnblogs.com/codingtmd/archive/2013/01/28/5078914.html

你可能感兴趣的文章
学习第一周
查看>>
Linux解决用户密码过期但不用修改密码的方法
查看>>
ORA-00245: control file backup operation failed
查看>>
快速掌握Redis——第二招:安装
查看>>
使用jekyll搭建自己的博客系统
查看>>
从Jetty、Tomcat和Mina中提炼NIO构架网络服务器的经典模式(一)
查看>>
Windows 10之 隐藏“此电脑”窗口的6个额外文件夹
查看>>
struct2源码解读(10)之执行action请求前篇
查看>>
Linux下的进程江湖
查看>>
15.1异常处理
查看>>
nginx和lua的协程
查看>>
HAProxy负载均衡web服务
查看>>
chkconfig命令
查看>>
mysql修改替换某个字段的某些值
查看>>
初学者学习Linux之NFS
查看>>
服务搭建基础篇 dhcp服务
查看>>
救援模式
查看>>
SyilxOS块设备CACHE管理
查看>>
golang build error: syntax error: nested func not allowed
查看>>
linux系统编辑神器 -vim用法大全
查看>>