Convert Sorted List to Binary Search Tree LeetCode
来源:互联网 发布:qt网络编程 tcp连接 编辑:程序博客网 时间:2024/06/05 05:02
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; } * } *//** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private ListNode current; public int getListLength(ListNode head) { if (head == null) { return 0; } int size = 0; ListNode temp = head; while (temp != null) { size++; temp = temp.next; } return size; } public TreeNode getCurrentTreeNodeHelper(int size) { if (size == 0) { return null; } TreeNode left = getCurrentTreeNodeHelper(size / 2); TreeNode root = new TreeNode(current.val); current = current.next; TreeNode right = getCurrentTreeNodeHelper(size - 1 - size / 2); root.left = left; root.right = right; return root; } public TreeNode sortedListToBST(ListNode head) { current = head; int size = getListLength(head); TreeNode dummy = getCurrentTreeNodeHelper(size); return dummy; }}
0 0
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode[Tree]: Convert Sorted List to Binary Search Tree
- [leetcode][list][dfs] Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- LeetCode : Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Balanced Binary Search Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- leetcode 66: Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- [Leetcode]Convert Sorted List to Binary Search Tree
- [leetcode]Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Binary Search Tree
- NodeJS基本知识
- 使用Qt的qmake管理boost::filesystem代码时出现LNK2019问题
- 8张图理解Java
- 使用 JWT 让你的 RESTful API 更安全
- Ubuntu 删除两个文件夹下相同文件名的文件(内容也完全相同)
- Convert Sorted List to Binary Search Tree LeetCode
- 拦截用户登录切面分析
- tableHeaderView的Masonry
- STL 的各个版本
- 编译glew
- volley为什么能够支持android-6.0
- Linux下端口占用查看
- 一个调用webservice的php基类
- Xcode compile rocket always failed with exit code 5