Tree: Preorder Traversal

  • + 0 comments

    Recursive Method- TC is O(n log n) and SC is O(1)

    def preOrder(root):

    if root is not None:
        print(root.info,end=" ")
        preOrder(root.left)
        preOrder(root.right)
    

    Iterative Method- TC is O(n) and SC is O(1)

    def preOrder(root):

    stack= [root]
    result = []
    
    if root is None:return []
    
    while stack:
        root = stack.pop()
        result.append(root.info)
        if root.right:
            stack.append(root.right)
        if root.left :
            stack.append(root.left)
    print (*result)