0144. Preorder Traversal
Easy | Binary Tree + Traversal | 4 ms (99.93%), 13.3 MB (95.41%)
Source: LeetCode - Binary Tree Preorder Traversal GitHub: Solution / Performance
Given the root
of a binary tree, return the preorder traversal of its nodes' values.
Pop the stack to retrieve the current node and append the current node's value
Push left-child and then right-child node onto the stack if existing
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
# (base case)
if not root: return []
if not root.left and not root.right: return [root.val]
# ==================================================
# Binary Tree + Pre-order Traversal =
# ==================================================
# time : O(n)
# space : O(n)
ans = []
stack = [root]
while stack:
node = stack.pop()
ans.append(node.val)
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return ans
'''
# ==================================================
# Binary Tree + Pre-order Traversal =
# ==================================================
# time : O(n)
# space : O(n)
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
'''
Last updated
Was this helpful?