Programming Camp – Algorithm Training Camp – Day 14

Two Strategies to traverse a binary tree 

1. Breadth First Search (BFS)

Scan through the tree level by level, following the order of height, from top to bottom. The nodes on the higher level would be visited before the ones on the lower levels.

2. Depth First Search (DFS)

Depth has priority in this strategy so that the search would start from a root and reach all the way down to a certain leaf, and then back to the root to reach another branch.

DFS can further be distinguished as preorder, inorder and postorder depends on the relative order among the root node, left node and right node.

 Leetcode Problems

1. Binary Tree Preorder Traversal (Leetcode Number: 144)

node -> left -> right

class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if root is None:
            return []
        
        # Create stack to store the node and respective child nodes separately
        stack, res = [root],  []
        
        # Put the left nodes at the end of stack as the pop() function extract last element first
        while stack:
            root = stack.pop()
            if root is not None:
                res.append(root.val)
                if root.right is not None:
                    stack.append(root.right)
                if root.left is not None:
                    stack.append(root.left)
        
        return res
        

2. Binary Tree Postorder Traversal (Leetcode Number: 145)

left -> right -> node

class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        
        def posterorder(root):
            if root is None:
                return
            
            posterorder(root.left)
            posterorder(root.right)
            res.append(root.val)
        
        posterorder(root)
        return res

3. Binary Tree Inorder Traversal (Leetcode Number: 94)

left -> node -> right

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        
        def inorder(root):
            if root is None:
                return
            
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)
        
        inorder(root)
        return res

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值