Skip to content

Commit a3061aa

Browse files
authored
Create check_if_path_exists.py
1 parent 0db2d9a commit a3061aa

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Check if a given path exists in a tree
2+
3+
# Traverse the tree in preorder fashion and keep matching the node
4+
# value to the index of the given path
5+
6+
class Node:
7+
8+
def __init__(self, val):
9+
self.val = val
10+
self.right = None
11+
self.left = None
12+
13+
14+
def check_path(root, arr, n, index):
15+
if root is None:
16+
return n == 0
17+
18+
if root.left == None and root.right == None and root.val == arr[index] and index == n -1:
19+
return True
20+
21+
return (index < n) and (root.val == arr[index]) and (check_path(root.left, arr, n, index + 1) or check_path(root.right, arr, n, index + 1))

0 commit comments

Comments
 (0)