Leetcode 之Convert Sorted List to Binary Search Tree(55)
2023-09-14 08:57:33 时间
和上题思路基本一致,不同的地方在于,链表不能随机访问中间元素。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int listLength(ListNode* node) { int n = 0; while (node) { n++; node = node->next; } return n; } ListNode* nth_node(ListNode* node, int n) { while (--n)node = node->next; return node; } TreeNode* sortedListToBST(ListNode* head) { sortedListToBST(head, listLength(head)); } TreeNode* sortedListToBST(ListNode* head, int len) { if (len == 0)return nullptr; if (len == 1)return new TreeNode(head->val); TreeNode* root = new TreeNode(nth_node(head, len / 2 + 1)->val); root->left = sortedListToBST(head, len / 2); root->right = sortedListToBST(head, len / 2 + 2); return root; }
相关文章
- LeetCode 第 196 场周赛 (题目:5452-5455,这是参加过最坑的周赛,暴力n^2居然可以过)
- Java实现 LeetCode 399 除法求值
- Java实现 LeetCode 62 不同路径
- Java实现 LeetCode 55 跳跃游戏
- Java实现LeetCode #986 - Interval List Intersections
- (LeetCode 203)Remove Linked List Elements
- 每日一道 LeetCode (38):Excle 表列名称
- LeetCode: 102_Binary Tree Level Order Traversal | 二叉树自顶向下的层次遍历 | Easy
- (LeetCode 86)Partition List
- [LeetCode] Odd Even Linked List
- [LeetCode] Linked List Cycle II
- [LeetCode] Insertion Sort List
- Leetcode 最长连续序列
- [LeetCode] 83. Remove Duplicates from Sorted List ☆(从有序链表中删除重复项)
- leetcode - Rotate List
- leetcode 19 -- Remove Nth Node From End of List
- leetcode 551. Student Attendance Record I
- leetcode 237. Delete Node in a Linked List
- 【Leetcode刷题Python】从列表list中创建一颗二叉树
- 【LeetCode】120.三角形最小路径和