Convert Sorted List to Binary Search Tree
来源:互联网 发布:云计算产业的盈利模式 编辑:程序博客网 时间:2024/06/06 00:33
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
public TreeNode sortedListToBST(ListNode head) { // base case if (head == null) return null; ListNode slow = head; ListNode fast = head; ListNode prev = null; // find the median node in the linked list, after executing this loop // fast will pointing to the last node, while slow is the median node. while (fast.next != null) { fast = fast.next; if (fast.next == null) { break; } fast = fast.next; prev = slow; slow = slow.next; } if (prev != null) prev.next = null; else head = null; TreeNode root = new TreeNode(slow.val); root.left = sortedListToBST(head); root.right = sortedListToBST(slow.next); return root; }
public TreeNode sortedListToBST(ListNode head) { if(head == null){ return null; } int size = 0; ListNode runner = head; node = head; while(runner != null){ runner = runner.next; size ++; } return inorderHelper(0, size - 1);}public TreeNode inorderHelper(int start, int end){ if(start > end){ return null; } int mid = start + (end - start) / 2; TreeNode left = inorderHelper(start, mid - 1); TreeNode treenode = new TreeNode(node.val); treenode.left = left; node = node.next; TreeNode right = inorderHelper(mid + 1, end); treenode.right = right; return treenode;}
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
- 优秀项目经理应备技能02-项目的定义与特性
- Fiddler工具使用-抓取https请求
- 显示图片,VS2010, MFC, OpenCV2
- 九度OJ 题目1209:最小邮票数
- 平衡二叉树的实现代码
- Convert Sorted List to Binary Search Tree
- WordPress安装折腾
- HDOJ 1217 Arbitrage(拟最短路,floyd算法)
- 【面试】C\C++程序基础1
- 九度OJ 题目1079:手机键盘
- 运维故障总结
- 奔跑吧小子 v1.0.3 安卓版
- OpenCV------- 对XML和YAML文件实现I/O操作
- hdu1021Fibonacci Again