Travsese a tree

遍历Tree, 基本上是两种套路: DFS(preorder, inorder, postorder) 和 BFS.

遍历

Inorder traversal could be implemented in three different ways: recursive(递归), iterative(迭代) and Morris.

迭代: 使用stack, 顺序与途中一致。
模板:

 stack, inorder = [], float('-inf')
        
        # inorder traversal : left -> node -> right
        while stack or root:
            # 1. go left till you can
            while root:
                stack.append(root)
                root = root.left
                
            # 2. all logic around the node
            root = stack.pop()
           
            # 3. go one step right
            root = root.right

你可能感兴趣的:(Travsese a tree)