0% found this document useful (0 votes)
1 views2 pages

Python Trees Cheatsheet

This document provides a comprehensive overview of trees in Python, including definitions, common terminology, and traversal methods such as DFS (preorder, inorder, postorder) and BFS. It also outlines the properties of binary search trees and common problems associated with trees, such as finding height and checking balance. Additionally, it offers tips for effectively working with tree structures in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

Python Trees Cheatsheet

This document provides a comprehensive overview of trees in Python, including definitions, common terminology, and traversal methods such as DFS (preorder, inorder, postorder) and BFS. It also outlines the properties of binary search trees and common problems associated with trees, such as finding height and checking balance. Additionally, it offers tips for effectively working with tree structures in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Recursion Cheat Sheet

Python Trees Cheat Sheet

1. What are Trees?


- A tree is a hierarchical data structure with nodes.
- Each tree has a root node and zero or more child nodes.
- Special case: Binary Tree - each node has at most 2 children.

2. Common Terminology:
- Root: Topmost node.
- Parent/Child: Relationship between nodes.
- Leaf: Node with no children.
- Depth: Distance from root to node.
- Height: Distance from node to deepest leaf.

3. Binary Tree Traversals (DFS):


Preorder (Root, Left, Right):
def preorder(node):
if node:
print(node.val)
preorder(node.left)
preorder(node.right)

Inorder (Left, Root, Right):


def inorder(node):
if node:
inorder(node.left)
print(node.val)
inorder(node.right)

Postorder (Left, Right, Root):


def postorder(node):
if node:
postorder(node.left)
postorder(node.right)
print(node.val)

4. Breadth-First Search (BFS) / Level Order:


from collections import deque
def bfs(root):
q = deque([root])
Python Recursion Cheat Sheet

while q:
node = q.popleft()
print(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)

5. Binary Search Tree (BST) Property:


- Left subtree values < root value < right subtree values.

6. Common Tree Problems:


- Find height of a tree.
- Count nodes / leaves.
- Check if a tree is balanced.
- Lowest Common Ancestor (LCA).

7. Tips:
- Use recursion for DFS; use a queue for BFS.
- Visualize the tree for better understanding.
- For large trees, iterative solutions may be more memory-efficient.

You might also like