Convert Sorted List to Binary Search Tree
来源:互联网 发布:淘宝情趣用品货源 编辑:程序博客网 时间:2024/04/29 03:55
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
这道题目相比其他的binary tree 以及linked list 题目要难一些,理解也更抽象一些
一种比较容易想到的方法是每次都用一个 low 一个fast 指针来找重点,这样子需要重复遍历。
更加smart 的方法是下面的实现,用cur 做了一次遍历。 但是比较容易出错。
例如 1,2 ,3,4,5,6,7 //7个listnodes, size 分别表示还需要convert 的有几个值
1:对于1,2 ,3,4,5,6,7 : (1,2,3)<-----------4---------->(5,6,7)
------------------------------------------- left 剩 3 个(size/2) 根 right 剩 3 个 (size - (size/2 + 1))
2:对于1,2,3: (1)<- 2-> (3)
3:对于1: (null) 1 (null)
//此时 1 的左右都为null,即 size 为0,说明 1为leaf,直接返回
cur 开始为1,除了toBST(0), 当size不为0时,每一次BST操作,则cur=cur.next.
/** * 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 { ListNode cur; public TreeNode sortedListToBST(ListNode head) { if (head == null) { return null; } int size = getSize(head); cur = head; return toBST(size); } private TreeNode toBST(int size) { if (size <= 0) { return null; } TreeNode leftTreeNode = toBST(size / 2 ); TreeNode root = new TreeNode(cur.val); cur = cur.next; TreeNode rightTreeNode = toBST(size - size / 2 - 1); root.left = leftTreeNode; root.right = rightTreeNode; return root; } private int getSize(ListNode head) { if (head == null) { return 0; } else { int count = 0; while (head != null) { count ++; head = head.next; } return count; } }}
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
- 简单的内置logging设计
- Python 对Twitter tweet的元素 (Word, Screen Name, Hash Tag)的频率分析
- VHDL tips
- 情书
- [three.js] 解決貼圖無法重複的問題 Solving with Texture RepeatWrapping Fail Issue
- Convert Sorted List to Binary Search Tree
- 美国加州购物旅游
- WebGL and OpenGL Differences - 非2的次幂纹理的那些讲究儿
- myeclipse 安装jad 查看jar包源码
- 風山漸
- ASP.NET控件ID, ClientID, UniqueID区别
- android应用开发的几个重要概念
- 回调函数在非阻塞模式中的使用
- 我的第一篇博客