codingpython
Binary tree - DFS
Write a function called dfs which takes in the root node of a binary tree and performs depth first search on the tree, printing each node’s value as it’s visited. Use the below data structure. What is the time complexity of this function?
pythonclass Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = Node(
10,
left=Node(
5,
left=Node(3),
right=Node(7)
),
right=Node(
15,
left=Node(12),
right=Node(
20,
left=Node(17),
right=Node(25)
)
)
)
'''
10
/ \
5 15
/ \ / \
3 7 12 20
/ \
17 25
'''