Algorithmsbinary tree
Binary Tree — At Most Two Children
TT
Testlaa Team
May 14, 2026•1 min read
Each node has left and right references (either may be None). This is the default model for most coding interviews.
Try this in Python
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: TreeNode | None = None
right: TreeNode | None = None
def preorder_vals(root: TreeNode | None) -> list[int]:
if not root:
return []
return [root.val] + preorder_vals(root.left) + preorder_vals(root.right)
r = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4)))
print(preorder_vals(r))
Key takeaways
- Recursion depth equals tree height in the worst case—mind stack overflow on deep skewed trees.
- Iterative traversals use explicit stacks or queues.
- Decide inclusive semantics for empty trees early.
Tags:
Tree structuresPythonStudents
