-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkBinaryTree.py
81 lines (73 loc) · 1.37 KB
/
checkBinaryTree.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
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isBinaryTree(node):
q = [node]
while q:
curNode = q.pop(0)
if curNode.left:
if curNode.val <= curNode.left.val:
return False
q.append(curNode.left)
if curNode.right:
if curNode.val >= curNode.right.val:
return False
q.append(curNode.right)
return True
# 6
# / \
# 4 8
# / \
# 2 5
tree = Node(6,
Node(4,
Node(2),
Node(5)
),
Node(8)
)
assert isBinaryTree(tree)
# 6
# / \
# 4 8
# / \
# 2 3
tree = Node(6,
Node(4,
Node(2),
Node(3)
),
Node(8)
)
assert not isBinaryTree(tree)
# 6
# /
# 4
# /
# 2
tree = Node(6,
Node(4,
Node(2)
),
)
assert isBinaryTree(tree)
# 6
tree = Node(6)
assert isBinaryTree(tree)
# 6
# / \
# 4 8
# / \ \
# 2 5 9
tree = Node(6,
Node(4,
Node(2),
Node(5)
),
Node(8,
None,
Node(9))
)
assert isBinaryTree(tree)