-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
83 lines (77 loc) · 2.43 KB
/
utils.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
@classmethod
def build_bst_method1(cls, data: list):
if len(data) == 0 or all([_ is None for _ in data]):
return None
root_node = TreeNode(val=data[0])
for each_data in data[1:]:
if each_data is None:
continue
this_node = TreeNode(val=each_data)
p = root_node
while p:
if this_node.val < p.val:
if p.left:
p = p.left
else:
p.left = this_node
break
elif this_node.val > p.val:
if p.right:
p = p.right
else:
p.right = this_node
break
return root_node
@classmethod
def build_normal_tree_by_node_list(cls, data: list):
node_list = [None] * len(data)
if len(data) == 0:
return None
for index, each_data in enumerate(data):
node_list[index] = TreeNode(val=each_data)
for index, each_node in enumerate(node_list):
if each_node is None:
continue
if index * 2 + 2 <= len(node_list):
each_node.left = node_list[index * 2 + 1]
else:
break
if index * 2 + 3 <= len(node_list):
each_node.right = node_list[index * 2 + 2]
else:
break
return node_list[0]
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@classmethod
def build_linked_list(cls, data: list, none_head=True):
head = ListNode()
p = head
for each_data in data:
this_node = ListNode(each_data)
p.next = this_node
p = p.next
if none_head:
return head.next
else:
return head
@classmethod
def check_linked_list_equal(cls, l1, l2):
while l1 and l2:
if l1.val != l2.val:
return False
l1 = l1.next
l2 = l2.next
if l1 is None and l2 is None:
return True
else:
return False