leetcode109. 有序链表转换二叉搜索树
生活随笔
收集整理的這篇文章主要介紹了
leetcode109. 有序链表转换二叉搜索树
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個單鏈表,其中的元素按升序排序,將其轉(zhuǎn)換為高度平衡的二叉搜索樹。
本題中,一個高度平衡二叉樹是指一個二叉樹每個節(jié)點?的左右兩個子樹的高度差的絕對值不超過 1。
示例:
給定的有序鏈表: [-10, -3, 0, 5, 9],
一個可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面這個高度平衡二叉搜索樹:
? ? ? 0
? ? ?/ \
? ?-3 ? 9
? ?/ ? /
?-10 ?5
思路:
1)轉(zhuǎn)換成數(shù)組再做
2)鏈表直接做,快慢指針,時間慢。
3)按中序遍歷建樹,這樣可以順序遍歷鏈表建樹即可。
3見代碼
/*** 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; }* }*/ /*** 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; } }*/ class Solution {private ListNode head;private int findSize(ListNode head) {ListNode ptr = head;int c = 0;while (ptr != null) {ptr = ptr.next; c += 1;}return c;}private TreeNode convertListToBST(int l, int r) {if (l > r) {return null;}int mid = (l + r) / 2;TreeNode left = this.convertListToBST(l, mid - 1);TreeNode node = new TreeNode(this.head.val);node.left = left;this.head = this.head.next;node.right = this.convertListToBST(mid + 1, r);return node;}public TreeNode sortedListToBST(ListNode head) {int size = this.findSize(head);this.head = head;return convertListToBST(0, size - 1);} }?
總結(jié)
以上是生活随笔為你收集整理的leetcode109. 有序链表转换二叉搜索树的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 总结了线程安全性的二十四个精华问题
- 下一篇: 如何使用弱网环境来验证游戏中的一些延迟问