6/17/2020

[LeetCode] 94. Binary Tree Inorder Traversal

Problem : https://leetcode.com/problems/binary-tree-inorder-traversal/

Recursive Solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        def inorder(node):
            if node:
                yield from inorder(node.left)
                yield node.val
                yield from inorder(node.right)
        
        return list(inorder(root))
Iterative Solution:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        
        result = []
        stack = [root] if root else []
        
        while stack:
            node = stack[-1]
            
            if not node.left:
                result.append(node.val)
                stack.pop()
                
                if node.right:
                    stack.append(node.right)
                    node.right = None
            else:
                stack.append(node.left)
                node.left = None
        
        return result

Edited on 04/21/2021. Update recursive solution by using 'yeild' and 'yield from'.

Edited on 04/21/2021. Small refactor to iterative solution.

No comments:

Post a Comment