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.

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

Applications

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.

1589130-20190712093850713-1370018411.png

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

Python Implementation

Pre-order

# 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()
            result.append(cur.val)
            if cur.right:
                stack.append(cur.right)
            if cur.left:
                stack.append(cur.left)
        return result

In-order

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

Post-order

'''
This one refers to
https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45785/Share-my-two-Python-iterative-solutions-post-order-and-modified-preorder-then-reverse
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:
                    result.append(cur.val)
                else:
                    stack.append((cur, True))
                    stack.append((cur.right, False))
                    stack.append((cur.left, False))
        return result

转载于:https://www.cnblogs.com/shiina922/p/11173452.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值