[LeetCode] 109. 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.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
      0
     / \
   -3   9
   /   /
 -10  5
和 108. Convert Sorted Array to Binary Search Tree 思路一样,只不过一个是数组,一个是链表。数组可以通过index直接访问元素找到中点,而链表的查找中间点要通过快慢指针来操作。
Java:
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        return toBST(head,null);
    }
    public TreeNode toBST(ListNode head, ListNode tail){
        ListNode slow = head;
        ListNode fast = head;
        if(head==tail) return null;
        while(fast!=tail&&fast.next!=tail){
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode thead = new TreeNode(slow.val);
        thead.left = toBST(head,slow);
        thead.right = toBST(slow.next,tail);
        return thead;
    }
}   
Python:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None class Solution:
head = None
# @param head, a list node
# @return a tree node
def sortedListToBST(self, head):
current, length = head, 0
while current is not None:
current, length = current.next, length + 1
self.head = head
return self.sortedListToBSTRecu(0, length) def sortedListToBSTRecu(self, start, end):
if start == end:
return None
mid = start + (end - start) / 2
left = self.sortedListToBSTRecu(start, mid)
current = TreeNode(self.head.val)
current.left = left
self.head = self.head.next
current.right = self.sortedListToBSTRecu(mid + 1, end)
return current
Python:
def sortedListToBST(self, head):
if not head:
return
if not head.next:
return TreeNode(head.val) slow, fast = head, head.next.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next tmp = slow.next
slow.next = None
root = TreeNode(tmp.val)
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(tmp.next) return root
C++:
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        auto curr = head;
        int n = 0;
        while (curr) {
            curr = curr->next;
            ++n;
        }
        return BuildBSTFromSortedDoublyListHelper(&head, 0, n);
    }
    TreeNode * BuildBSTFromSortedDoublyListHelper(ListNode **head, int s, int e) {
        if (s == e) {
            return nullptr;
        }
        int m = s + ((e - s) / 2);
        auto left = BuildBSTFromSortedDoublyListHelper(head, s, m);
        auto curr = new TreeNode((*head)->val);
        *head = (*head)->next;
        curr->left = left;
        curr->right = BuildBSTFromSortedDoublyListHelper(head, m + 1, e);
        return curr;
    }
};
类似题目:
[LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树
All LeetCode Questions List 题目汇总
[LeetCode] 109. Convert Sorted List to Binary Search Tree 把有序链表转成二叉搜索树的更多相关文章
- [LeetCode] 108. Convert Sorted Array to Binary Search Tree 把有序数组转成二叉搜索树
		
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Fo ...
 - LeetCode 108. Convert Sorted Array to Binary Search Tree (有序数组转化为二叉搜索树)
		
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 题目 ...
 - convert sorted list to binary search tree(将有序链表转成平衡二叉搜索树)
		
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
 - 108. Convert Sorted Array to Binary Search Tree 109. Convert Sorted List to Binary Search Tree -- 将有序数组或有序链表转成平衡二叉排序树
		
108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascendin ...
 - Leetcode#109	Convert Sorted List to Binary Search Tree
		
原题地址 跟Convert Sorted Array to Binary Search Tree(参见这篇文章)类似,只不过用list就不能随机访问了. 代码: TreeNode *buildBST( ...
 - [LeetCode]  Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
		
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
 - leetcode 109  Convert Sorted List to Binary Search Tree   ----- java
		
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
 - Java for LeetCode 109 Convert Sorted List to Binary Search Tree
		
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
 - [leetcode]109. Convert Sorted List to Binary Search Tree链表构建二叉搜索树
		
二叉树的各种遍历方式都是可以建立二叉树的,例如中序遍历,就是在第一步建立左子树,中间第二步建立新的节点,第三步构建右子树 此题利用二叉搜索树的中序遍历是递增序列的特点,而链表正好就是递增序列,从左子树 ...
 
随机推荐
- Linux的rwx
 - 记一次用pip安装docker-compose报错及解决方法
			
Docker-Compose 的安装 方法一 # 下载1.25.0 docker compose sudo curl -L "https://github.com/docker/compos ...
 - 自动生成百度小程序sitemap.txt文件路径
			
因为业务需要,需要在目前项目上开发一个百度小程序,百度智能小程序上线了,但是内容每天得推送,不可能一个小程序路径一个推送吧,因为小程序路径和项目路径不一致. 因为项目是用ThinkPHP开发的,在此附 ...
 - oracle中LPAD和RPAD函数的使用方法(加个人总结)
			
今天看到两个没有见过的SQL中的函数,总结一下: 函数参数:lpad( string1, padded_length, [ pad_string ] ) 其中 string1:源字符串 padded_ ...
 - Jupyter notebook 自动补全
			
Jupyter notebook 自动补全 Jupyter notebook使用默认的自动补全是关掉的.要打开自动补全,需修改默认配置. ipython profile create 以上命令会 ...
 - php 常用操作数组函数
			
我们有很多操作数组的元素,我们这一节先讲一些.在6.3里面我们会总结更多的数组常用函数.深圳dd马达 下面的几个主要是移动数组指针和压入弹出数组元素的和个函数. 函数 功能 array_shift 弹 ...
 - 洛谷 [USACO05DEC] 布局 题解
			
今天学了差分约束系统, 这是一道板子题. 核心:a[v]>a[u]+d 相当于从u到v连一条长度为d的有向边.由于要判断有环,所以要从0点先跑一遍spfa因为1点不一定能到所有的点. #incl ...
 - S1_搭建分布式OpenStack集群_07 nova服务配置 (计算节点)
			
一.服务安装(计算节点)安装软件:# yum install openstack-nova-compute -y 编辑/etc/nova/nova.conf文件并设置如下内容:# vim /etc/n ...
 - Mysql 创建只读账户
			
mysql 创建只读账户: 1.查询所有账号信息 SELECT DISTINCT a.`User`,a.`Host`,a.password_expired,a.password_last_change ...
 - Linux 系统管理——引导过程与服务控制
			
一. 系统引导流程 1.开机自检(BIOS)(基本的输入输出系统) 2.MBR引导1.2. MBRIS 当从本机硬盘中启动系统时,首先根据硬盘第一个扇区中MBR (Master Boot Record ...