-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertSortedListToBinarySearchTree.h
48 lines (40 loc) · 1.28 KB
/
ConvertSortedListToBinarySearchTree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Author: naiyong, aonaiyong@gmail.com
Date: Sep 24, 2014
Problem: ConvertSortedListToBinarySearchTree.h
Difficulty: 4
Source: https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
Notes:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution: Bottom-up Recursion (A combination of In-order&Post-order Traversal).
Time: O(n), Space: O(log(n))
*/
#ifndef CONVERTSORTEDLISTTOBINARYSEARCHTREE_H_
#define CONVERTSORTEDLISTTOBINARYSEARCHTREE_H_
#include "TreeNode.h"
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
int n = getLength(head);
return sortedListToBST(head, n);
}
TreeNode *sortedListToBST(ListNode *&head, int n) {
if (n <= 0)
return nullptr;
TreeNode *left = sortedListToBST(head, n/2);
TreeNode *root = new TreeNode(head->val);
head = head->next;
root->left = left;
root->right = sortedListToBST(head, n-n/2-1);
return root;
}
int getLength(ListNode *head) {
int n = 0;
while (head) {
++n;
head = head->next;
}
return n;
}
};
#endif /* CONVERTSORTEDLISTTOBINARYSEARCHTREE_H_ */