Convert Sorted List to Binary Search Tree
来源:互联网 发布:御彩轩计划软件 编辑:程序博客网 时间:2024/06/15 15:34
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的区别是array可以用二分法,而list没法直接算mid。这时可用双指针,一个走快一个走慢的方法,找mid,然后再递归。
Source
/** * 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) { if(head == null) return null; ListNode p = head; ListNode q = head; ListNode pre = null; while(q.next!= null && q.next.next != null){ //注意判断条件 pre = p; p = p.next; q = q.next.next; } if(pre != null) pre.next = null; //注意pre==null的情况 TreeNode root = new TreeNode(p.val); if(pre != null) root.left = sortedListToBST(head); //注意pre==null的情况 root.right = sortedListToBST(p.next); return root; }}
Test
public static void main(String[] args){ ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); TreeNode a = new Solution().sortedListToBST(head); dfs(a); } public static void dfs(TreeNode a){ if(a == null) return; System.out.println(a.val); dfs(a.left); dfs(a.right); }
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
- 【翻译原创】(三)MonkeyTalk 用户手册 - IDE 及 Agent 的安装
- Quick-Cocos2d-x UI容器项拷贝
- mysql数据类型
- UINCODE字符串和安全字符串函数
- 函数逼近方法
- Convert Sorted List to Binary Search Tree
- 一位ACMer过来人的心得
- print与flush
- FPGA芯片结构
- try...except遇到的问题
- Appium Wrapper for Java
- Lex与Yacc学习(五)之正则表达式篇
- Maximum Gap
- 静思语