Convert Sorted List to Binary Search Tree
来源:互联网 发布:淘宝修改宝贝详情影响 编辑:程序博客网 时间:2024/05/01 12:41
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:这题应该与 Convert Sorted Array to Binary Search Tree 联系起来考虑,这样思路就很清晰了。
准确的说,都是root应该是中点,左子树比root小,右子树比root大,首先应该找root,然后用recursion循环去build左右子树。
注意:fast != end && fast.next != end.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } *//** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; return build(head, null); } public TreeNode build(ListNode start, ListNode end){ if(start == end){ return null; } ListNode slow = start; ListNode fast = start; while(fast!= end && fast.next!=end){ slow = slow.next; fast = fast.next.next; } TreeNode node = new TreeNode(slow.val); node.left = build(start,slow); node.right = build(slow.next, end); return node; }}
0 0
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- convert sorted list to binary search tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- SQL Server 2014 安装
- Python 第一章 基础知识
- DTP的优化
- 基于Scala的REST框架Spray
- Win7系统不识别usb键盘
- Convert Sorted List to Binary Search Tree
- 细聊代理模式
- 各种分类算法的优缺点
- 版本管理学习
- Visual Studio快捷键大全
- 第一个博文
- UE4 UnrealEngine4 中 实现多通道技术
- 【9912】采药
- jquery实现按回车触发事件