Skip to content

Commit 346bff9

Browse files
committed
1104
1 parent c223795 commit 346bff9

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,9 @@ Feel free to add issues, create pull requests and be a contributer.
148148
## Recursion
149149
| Website | Title | Solution | Time | Space | Difficulty | Note|
150150
|---------------- |---------------- | ----------- | --------------- | --------------- | ------------- |-----|
151-
| Leetcode | [654. Maximum Binary Tree](https://leetcode.com/contest/leetcode-weekly-contest-44/problems/maximum-binary-tree/) | [Java](./java/ConstructMaximumBinaryTree.java) | _O(n log n)_ | _O(n)_ | Easy | |
152151
| Leetcode | [50. Pow(x, n)](https://leetcode.com/problems/powx-n/description/) | [Java](./java/myPow.java) | _O()_ | _O(n)_ | Medium | |
152+
| Leetcode | [654. Maximum Binary Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/) | [Java](./java/sortedListToBST.java) | _O(n)_ | _O(logn)_ | Medium | |
153+
| Leetcode | [654. Maximum Binary Tree](https://leetcode.com/contest/leetcode-weekly-contest-44/problems/maximum-binary-tree/) | [Java](./java/ConstructMaximumBinaryTree.java) | _O(n log n)_ | _O(n)_ | Easy | |
153154

154155

155156
## Recursion

java/sortedListToBST.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* int val;
13+
* TreeNode left;
14+
* TreeNode right;
15+
* TreeNode(int x) { val = x; }
16+
* }
17+
*/
18+
class Solution {
19+
public TreeNode sortedListToBST(ListNode head) {
20+
21+
if(head == null) return null;
22+
if(head.next == null)
23+
return new TreeNode(head.val);
24+
25+
ListNode prev = null, slow = head, fast = head;
26+
27+
while(fast != null && fast.next != null)
28+
{
29+
prev = slow;
30+
slow = slow.next;
31+
fast = fast.next.next;
32+
}
33+
prev.next = null;
34+
TreeNode root = new TreeNode(slow.val);
35+
root.left = sortedListToBST(head);
36+
root.right = sortedListToBST(slow.next);
37+
38+
return root;
39+
}
40+
}

0 commit comments

Comments
 (0)