A binary tree node stores a value plus left/right child links. DFS uses O(h) extra space, BFS uses O(w), and every traversal below visits each node once: O(n).
| Python | Go | TypeScript | C++ |
|---|---|---|---|
class Node: |
type Node struct { |
type TreeNode = { |
struct Node { |
| operation | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| preorder root, left, right O(n) |
def preorder(root): |
visit(n.Val); dfs(n.Left); dfs(n.Right) |
visit(n.val); dfs(n.left); dfs(n.right) |
visit(n->val); dfs(n->left); dfs(n->right) |
| inorder left, root, right O(n) |
def inorder(root): |
func inorder(n *Node) { |
function inorder(n: TreeNode | null): void { |
void inorder(Node* n) { |
| postorder left, right, root O(n) |
def postorder(root): |
dfs(n.Left); dfs(n.Right); visit(n.Val) |
dfs(n.left); dfs(n.right); visit(n.val) |
dfs(n->left); dfs(n->right); visit(n->val) |
| operation | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| preorder O(n) |
def preorder_iter(root): |
[]*Node stack; push right then left |
TreeNode[] stack; push right then left |
vector<Node*> stack; push right then left |
| inorder O(n) |
def inorder_iter(root): |
walk left; pop; visit; go right |
walk left; pop; visit; go right |
walk left; pop; visit; go right |
| postorder O(n) |
def postorder_iter(root): |
stack of (node, seen); visit when seen |
stack of [node, seen]; visit when seen |
stack<pair<Node*, bool>>; visit when seen |
| operation | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| queue length snapshot O(n) |
from collections import deque |
for len(q) > 0 { |
let head = 0; |
while (!q.empty()) { |
| operation | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| answer at node = f(children) O(n) |
def height(root): |
func height(n *Node) int { |
function height(n: TreeNode | null): number { |
int height(Node* n) { |
| Python | Go | TypeScript | C++ |
|---|---|---|---|
|
|
|
|
Docs: docs.python.org · pkg.go.dev · developer.mozilla.org · en.cppreference.com