Skip to content

Commit 2cf191c

Browse files
authored
Create print_all_root_to_leaf_paths.py
1 parent e32d7da commit 2cf191c

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Traverse the tree in preorder fashion
2+
# append value in stack
3+
# if root.left and root.right is None, then print all stack values
4+
# traverse left
5+
# traverse right
6+
# pop from stack
7+
8+
class Node:
9+
10+
def __init__(self, val):
11+
self.val = val
12+
self.right = None
13+
self.left = None
14+
15+
16+
def print_route(root, stack):
17+
if root == None:
18+
return
19+
20+
stack.append(root.val)
21+
if root.left == None and root.right == None:
22+
for i in stack:
23+
print(i, end=' ')
24+
print()
25+
26+
print_route(root.left, stack)
27+
print_route(root.right, stack)
28+
stack.pop()
29+
30+
31+
root = Node(1)
32+
root.left = Node(2)
33+
root.right = Node(3)
34+
root.left.left = Node(4)
35+
root.left.right = Node(5)
36+
37+
print_route(root, [])

0 commit comments

Comments
 (0)