Binary Tree Traversals

Updated on July 12, 2019

3 Traversal Methods

  • In pre-order each parent node is visited before (pre) its children.
  • In in-order each parent node is visited in between its children.
  • In post-order each parent node is visited after (post) its children.

These three terms inorder, preorder and postorder are kept on the order pf processing of ROOT element.
Now when we say INORDER, it means everything is in order i.e. we traverse from left to root to right.
Take an example of a line segment with left end point A and right end point B. Take a mid point M on AB. Now inorder means starting from left (A) going to mid (M) and reaching right (R). As simple as that, everything is in order.
PREORDER means before order. Now what is before? Since i already said the names are kept keeping in mind the root element so the ROOT is before all the elements. So the root will be processed before any element. But remember, the left node will always be processed before right node.
Same goes with POSTORDER. The ROOT element will be processed at last after LEFT and RIGHT nodes have been processed.

How did preorder, inorder, and postorder binary tree traversals get their names? - Quora,
How to remember preorder, postorder and inorder traversal - Quora.


See data structures - When to use Preorder, Postorder, and Inorder Binary Search Tree Traversal strategies - Stack Overflow for applications.

The pic below comes from LeetCode explore card for recursion II.

In-order traversal can be used to solve LeetCode 98. Validate Binary Search Tree.

Python Implementation


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        stack = [root]
        result = []
        while stack:
            cur = stack.pop()
            if cur.right:
            if cur.left:
        return result


class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        stack = []
        result = []
        cur = root
        while stack or cur:
            while cur:
                cur = cur.left
            cur = stack.pop()
            cur = cur.right
        return result


This one refers to
His solution has the same runtime and memory usage as my original code, but is cleaner.
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        stack = [(root, False)]
        result = []
        while stack:
            cur, visited = stack.pop()
            if cur:
                if visited:
                    stack.append((cur, True))
                    stack.append((cur.right, False))
                    stack.append((cur.left, False))
        return result
posted @ 2019-07-11 23:16  resolvent  阅读(352)  评论(0编辑  收藏  举报