Binary Tree
binary-tree
Data Structures
Binary Search Tree (BST)
Run an inorder traversal on a **Binary Search Tree (BST)** of any size and the keys come out sorted, in `O(n)` time and `O(h)` space, with no separate sort step. That single property (an ordering invariant baked into the structure itself) is what turns a generic binary tree into a logarithmic-time search container that powers Java's `TreeMap`, C++ `std::map`, and the conceptual model behind every database index. This lesson covers the BST property (left subtree keys less than the node, right subtree keys greater), search and insert that follow the invariant, the three deletion cases (leaf, one child, two children resolved by inorder successor or predecessor), and the validation problem that interviewers love because the naive `node.left.val < node.val` check is wrong. You will also analyze the gap between the balanced `O(log n)` and the degenerate `O(n)` chain that motivates the next lesson. In **Trees: Binary Tree Fundamentals**, you implemented preorder, inorder, postorder, and level-order traversals; the BST property is what makes inorder special, because it now produces sorted output for free. Next, **Balanced BST (AVL / Red-Black)** addresses the elephant in the room: an unlucky insertion order can degrade a BST to a linked list, and self-balancing rotations are the fix.
Not Started
0%
Trees: Binary Tree Fundamentals
Every web page you load is a tree (the DOM), every directory you `cd` into is a tree, every JSON document with nested objects is a tree, and every arithmetic expression a compiler parses is a tree. **Binary Tree Fundamentals** turns that ubiquitous shape into a precise data structure where each node has at most two children, named `left` and `right`. This lesson covers the vocabulary you need for the rest of the curriculum (root, leaf, parent, child, sibling, depth, height), the four common shape categories (full, complete, perfect, balanced) and the degenerate case that collapses to a chain, all four canonical traversals (preorder, inorder, postorder, and level-order BFS), and both recursive and iterative implementations of each. You will also analyze why traversals are `O(n)` time but only `O(h)` space when written recursively. In **Queue & Deque**, you saw that a FIFO queue processes items in arrival order; level-order traversal is exactly that pattern applied to tree nodes. In **Hash Map (Dictionary) Basics**, the bucket-by-key idea reappears here when you store parent-pointer mappings or memoize subtree results during a traversal. With binary trees in your toolkit, **Binary Search Tree (BST)** layers an ordering invariant on top to turn the same shape into a logarithmic-time search structure.
Not Started
0%
Heaps & Priority Queue
Pull the next task in priority order from a stream of millions, and a sorted array gives you `O(1)` extract but `O(n)` insert; a sorted linked list flips the costs but stays linear; a balanced BST hits `O(log n)` for both but with substantial pointer overhead. A **Heap** quietly outperforms all three for this exact workload by storing a complete binary tree in a flat array and keeping just the min (or max) at the root. This lesson covers the heap property, the parent-and-child index formulas (`parent = (i-1)/2`, `left = 2i+1`, `right = 2i+2`) that let array indices encode tree structure with no pointers, sift-up and sift-down for `O(log n)` insert and extract, and the linear-time `heapify` build. You will see how this maps onto the priority queue abstraction and onto interview staples such as top-K elements, K-th largest, merge K sorted lists, and the streaming median with two heaps; on the systems side, the same structure powers Dijkstra and Prim. In **Trees: Binary Tree Fundamentals**, you saw what a complete binary tree is and how to traverse one; the heap reuses that exact shape but stores it implicitly. **Arrays & Strings** is what makes the implicit storage cheap: a flat array gives `O(1)` parent and child access through arithmetic, with no allocations per node. Next, **Binary Search Tree (BST)** trades the heap's partial ordering for a full ordering invariant, unlocking sorted iteration and key-based search at the cost of needing actual pointers.
Not Started
0%
Algorithms
Tree Algorithms
An invert-binary-tree problem famously got Max Howell rejected from Google in 2015, and the joke landed because the canonical solution is three lines of recursion. Trees show up everywhere in interviews precisely because they reward a particular kind of thinking: the answer for a node is almost always a function of the answers for its left and right subtrees, computed recursively, combined at the parent. **Tree Algorithms** trains that decomposition habit across a wide range of problems. You will implement BST insert, search, delete, validation, and the kth-smallest in-order trick. You will compute lowest common ancestor in both a generic binary tree and a BST. You will measure height, diameter, and width, and walk through path-sum problems, root-to-leaf enumeration, and the deceptively tricky maximum-path-sum-between-any-two-nodes. Structural operations include invert, mirror check, flatten to linked list, and serialize and deserialize. The lesson finishes with reconstructing a tree from inorder plus preorder or inorder plus postorder. In **Trees: Binary Tree Fundamentals**, you learned how nodes, children, and the four traversal orders work. **Recursion Fundamentals** gave you the call-stack mental model that every tree algorithm here relies on; tree recursion is essentially recursion with two recursive calls per frame. Next, **Graph Algorithms (Core)** removes the tree assumption (no cycles, no shared nodes) and tackles the more general traversal problems that result.
Not Started
0%
Practice Problems
Balanced Binary Tree
Given the root of a binary tree, determine if it is height-balanced (the depth of the two subtrees of every node never differs by more than one).
Count Complete Tree Nodes
Given the root of a complete binary tree, return the number of nodes in the tree.
Diameter of Binary Tree
Given the root of a binary tree, return the length of the diameter (the longest path between any two nodes, measured in edges).
Invert Binary Tree
Given the root of a binary tree, invert the tree (mirror it) and return its root.
Lowest Common Ancestor of a BST
Given a binary search tree and two nodes, find their lowest common ancestor by leveraging the BST property.
Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth (the number of nodes along the longest path from root to leaf).
Path Sum
Given the root of a binary tree and a target sum, determine if the tree has a root-to-leaf path that sums to the target.
Same Tree
Given the roots of two binary trees, determine if they are the same (structurally identical with the same node values).
Convert Sorted Array to Binary Search Tree
Given a sorted array, convert it into a height-balanced binary search tree using divide and conquer.
Subtree of Another Tree
Given the roots of two binary trees, determine if the second tree is a subtree of the first tree.
Symmetric Tree
Given the root of a binary tree, check whether it is a mirror of itself (symmetric around its center).
Binary Tree Maximum Path Sum
Given the root of a binary tree, return the maximum path sum where a path is any sequence of connected nodes (not necessarily passing through the root).
Serialize and Deserialize Binary Tree
Design an algorithm to serialize a binary tree to a string and deserialize the string back to the original tree.
Average of Levels in Binary Tree
Given the root of a binary tree, return the average value of the nodes on each level as an array.
Binary Tree Level Order Traversal
Given the root of a binary tree, return the level order traversal of its nodes' values (from left to right, level by level).
Binary Tree Right Side View
Given the root of a binary tree, return the values of the nodes you can see when looking at the tree from the right side, ordered from top to bottom.
Binary Search Tree Iterator
Implement an iterator over a BST that returns elements in ascending order (in-order traversal).
Binary Tree Zigzag Level Order Traversal
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values (alternating left-to-right and right-to-left for each level).
Construct BT from Inorder and Postorder
Given inorder and postorder traversal arrays, construct the binary tree and return its root.
Construct BT from Preorder and Inorder
Given preorder and inorder traversal arrays, construct the binary tree and return its root.
Count Good Nodes in Binary Tree
Given a binary tree root, count the number of 'good' nodes where no node on the path from root to that node has a value greater than the node's value.
Flatten Binary Tree to Linked List
Given the root of a binary tree, flatten the tree into a linked list in-place using the right pointers in preorder traversal order.
Kth Smallest Element in a BST
Given the root of a BST and an integer k, return the kth smallest value (1-indexed) using in-order traversal.
Lowest Common Ancestor of Binary Tree
Given a binary tree and two nodes, find their lowest common ancestor (the deepest node that is an ancestor of both).
Minimum Absolute Difference in BST
Given a BST, find the minimum absolute difference between the values of any two different nodes using in-order traversal.
Path Sum II
Given the root of a binary tree and a target sum, return all root-to-leaf paths where the sum of the values equals the target.
Populating Next Right Pointers II
Given a binary tree, populate each node's next pointer to point to its next right node. If there is no next right node, set it to null.
Sum Root to Leaf Numbers
Given a binary tree where each node contains a digit 0-9, find the total sum of all root-to-leaf numbers.
Validate Binary Search Tree
Given the root of a binary tree, determine if it is a valid binary search tree using bounds checking or in-order traversal.
Question Banks
Binary Tree Basics Quiz
Short prompts on node anatomy, depth vs height, and leaf counting. Foundation drills before tackling traversal, BSTs, or balanced tree problems.
Binary Search Tree Basics
Quick drills on the BST ordering invariant, in-order traversal yielding sorted output, and the most common search and insert operations.
Community
House Robber III
Maximize money robbed from a binary-tree neighborhood where no two directly-connected houses can both be robbed.
Trees and Binary Search Trees
What trees buy you over arrays and hash tables, why a textbook BST is almost never enough, and the balanced variants that actually run in production.
Cousins in Binary Tree
Decide whether two values in a binary tree are cousins (same depth, different parents).
Binary Tree Paths
Return every root-to-leaf path in a binary tree as a list of arrow-joined strings.
