~/snippets/Binary-Tree-Traversals
Published on

Binary Tree Traversals

102 words1 min read

Time Complexity: O(n)

n = size(tree)

def dfs(root: TreeNode):
    if (root is None): return
    # what I'm doing here ¯\_(ツ)_/¯
    print(root.val)
    dfs(root.left)
    dfs(root.right)
def bfs(root: TreeNode) -> None:
    if not root: return
    q = deque([root])

    while q:
        size = len(q)
        for i in range(size):
            node = q.popleft()
            # what I'm doing here ¯\_(ツ)_/¯
            print(str(node.val), end = " ")
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)

        print()