Convert Sorted List to Binary Search Tree
来源:互联网 发布:python基础编程第二版 编辑:程序博客网 时间:2024/06/05 17:25
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; next = null; } * } *//** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode sortedListToBST(ListNode head) { return constructBST(head); } public TreeNode constructBST(ListNode head){ if(head==null) return null; if(head.next==null) return new TreeNode(head.val); ListNode fast=head; ListNode slow=head; ListNode prev=null; while(fast!=null && fast.next!=null){ fast=fast.next.next; prev=slow; slow=slow.next; } if(prev!=null) prev.next=null; TreeNode tree=new TreeNode(slow.val); tree.left=constructBST(head); tree.right=constructBST(slow.next); return tree; }}
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
- MongoDB安装(Windows)
- 公用表表达式(Common Table Expression)
- Linux下Eclispe开发MapReduce环境搭建
- 最新v8编译以及使用
- QTableWidget详解(样式、右键菜单、表头塌陷、多选等)
- Convert Sorted List to Binary Search Tree
- void深入剖析
- C#——WinFrom——拖动(自定义的标题栏的窗体)不规则窗体
- Android动画之Interpolator和AnimationSet(三)
- JSR 303
- Express 4.x Node.js的Web框架
- Linux系统下自动删除前N天的日志文件
- 备忘-linux 环境变量设置
- Settings Bundle的multi value不显示,设置束的用法