Skip to content

Commit 57a7a72

Browse files
committed
Find multiple paths to leaf nodes
1 parent f3371a9 commit 57a7a72

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Trees/P04_RootToLeafPaths.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Author: OMKAR PATHAK
2+
3+
# Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in top-down fashion.
4+
# While traversing, store data of all nodes in current path in array path[]. When we reach a leaf node, print the path
5+
# array.
6+
7+
class Node(object):
8+
def __init__(self, data = None):
9+
self.left = None
10+
self.right = None
11+
self.data = data
12+
13+
def printPath(node, path = []):
14+
if node is None:
15+
return
16+
path.append(node.data)
17+
18+
if (node.left is None) and (node.right is None):
19+
print(' '.join([str(i) for i in path if i != 0]))
20+
else:
21+
printPath(node.left, path)
22+
printPath(node.right, path[0:1])
23+
24+
if __name__ == '__main__':
25+
root = Node(1)
26+
root.left = Node(2)
27+
root.right = Node(3)
28+
root.left.left = Node(4)
29+
root.right.left = Node(5)
30+
31+
printPath(root)

0 commit comments

Comments
 (0)