#144. Binary Tree Preorder Traversal | LeetCode Python Solution
Problem
LeetCode Problem
- Binary Tree Preorder Traversal
Python Solution without Recursion
# 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:
# Preorder (Root, Left, Right)
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# Return an empty list if there is no tree
if root is None:
return []
# Output list
output = []
# Push root node to stack
stack = [root]
while len(stack) > 0:
# Pop from stack
curr = stack.pop()
# Add the current node's value to the output list
output.append(curr.val)
# Push right node to stack
if curr.right is not None:
stack.append(curr.right)
# Push left node to stack
if curr.left is not None:
stack.append(curr.left)
return output