-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_bstDFS.py
More file actions
46 lines (40 loc) · 1.06 KB
/
12_bstDFS.py
File metadata and controls
46 lines (40 loc) · 1.06 KB
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
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self, root, val):
if root is None:
return TreeNode(val)
if root.val > val:
root.left = self.insert(root.left, val)
else:
root.right = self.insert(root.right,val)
return root
def preorder(self, root):
if root is None: return
print(root.val)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
if root is None: return
self.inorder(root.left)
print(root.val)
self.inorder(root.right)
def postorder(self, root):
if root is None: return
self.postorder(root.left)
self.postorder(root.right)
print(root.val)
p1 = TreeNode(7)
p1 = p1.insert(p1, 1)
p1 = p1.insert(p1, 15)
p1 = p1.insert(p1, 5)
p1 = p1.insert(p1, 6)
p1 = p1.insert(p1, 3)
p1 = p1.insert(p1, 8)
p1 = p1.insert(p1, 10)
p1 = p1.insert(p1, 11)
p1.preorder(p1)
p1.inorder(p1)
p1.postorder(p1)