Skip to content

Commit 3eac1b5

Browse files
committed
added Tree creation and traversal
1 parent f3647b5 commit 3eac1b5

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

tree/BFS_preorder_traversal.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class TreeNode:
2+
def __init__(self, data):
3+
self.data = data
4+
self.lnode = None
5+
self.rnode = None
6+
7+
8+
def preOrderTraversal(rootNode):
9+
if not rootNode:
10+
return
11+
print(rootNode.data)
12+
preOrderTraversal(rootNode.lnode)
13+
preOrderTraversal(rootNode.rnode)
14+
15+
16+
bt = TreeNode("Drinks")
17+
leftchild = TreeNode("hot")
18+
rightchild = TreeNode("cold")
19+
hotchild = TreeNode("Tea")
20+
coldchild = TreeNode("Cola")
21+
leftchild.lnode = hotchild
22+
rightchild.rnode = coldchild
23+
bt.lnode = leftchild
24+
bt.rnode = rightchild
25+
preOrderTraversal(bt)

tree/create_tree.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class TreeNode:
2+
def __init__(self, data, children=[]):
3+
self.data = data
4+
self.children = children
5+
6+
def __str__(self, level=0):
7+
ret = " " * level + str(self.data) + "\n"
8+
for child in self.children:
9+
ret += child.__str__(level+1)
10+
return ret
11+
12+
def addchild(self, TreeNode):
13+
self.children.append(TreeNode)
14+
15+
16+
tree = TreeNode('Drinks', [])
17+
cold = TreeNode('Cold', [])
18+
hot = TreeNode('Hot', [])
19+
tree.addchild(hot)
20+
tree.addchild(cold)
21+
coffee = TreeNode('Coffee', [])
22+
tea = TreeNode('Tea', [])
23+
cola = TreeNode('Cola', [])
24+
fanta = TreeNode('Fanta', [])
25+
cold.addchild(cola)
26+
cold.addchild(fanta)
27+
hot.addchild(tea)
28+
hot.addchild(coffee)
29+
30+
print(tree)

0 commit comments

Comments
 (0)