A Tree is a connected, acyclic, and hierarchical data structure consisting of nodes. One node is designated as the root, and every other node is connected by exactly on path from the root. Each node may have zero or more children, but exactly on parent (except for the root).
Key Properties of a Tree
Property | Description |
---|---|
Acyclic | A tree has no cycles |
Connected | There is a path between any two nodes |
Rooted | One node is called the root (typically at the top) |
N - 1 edges | A tree with N nodes always has exactly N - 1 edges |
Unique paths | There is exactly one path between any two nodes |
Directed (optional) | In rooted trees, edges are typically directed from parent to child |
A Node is a fundamental unit in a tree that holds data and can link to other nodes (children). Each node may contain a value, reference(s) to child node(s), and sometimes a reference to the parent.
An Edge is a connection or link between two nodes (typically from a parent to a child). In a tree with N nodes, there are exactly N - 1 edges.
A Root is the topmost node in a tree hierarchy. It has no parent. All other nodes descend from the root. A tree can have only one root.
A Leaf is a node that has no children. It is at the bottom of the tree structure. Also known as a terminal node.
A Parent is a node that has one or more children connected to it. It provides a link downward in the hierarchy.
A Child is a node that descends from another node. A child has exactly on parent (except in DAGs or general graphs).
Height is the length of the longest path from a node to a leaf. The height of a tree is the height of its root node.
Depth is the distance from the root to a given node (i.e., the number of edges in the path from root to that node). Root has depth 0.
Subtree is a subset of another tree. It consists of a node and all its descendants.
Degree of node is the number of children a node has. The degree of a tree is the maximum degree among all nodes in the tree.
1. Binary Tree: A tree in which each node has at most two children, referred to as the left and right child.
Foundational for more specialized trees like BSTs, heaps, and segment trees.
Properties
2. Binary Search Tree (BST): A special type of binary tree that maintains a sorted order.
Supports efficient searching, insertion, and deletion in O log n average time if balanced.
Properties
3. N-ary Tree: A tree in which can have any number of children.
Organizational charts, file systems, XML/HTML parsers, AI game trees.
If children N = 2, it becomes a binary tree.
Properties
4. Balanced Tree: A tree where the height difference between left and right subtrees for any node is at most 1 (in AVL), or height is kept logarithmic relative to the number of nodes.
Ensure O log n time complexity for operations.
Examples:
5. Unbalanced Tree A tree where the height can become skewed and not logarithmic, leading to degraded performance.
Inserting sorted elements into a BST without balancing can form a linked list like structure.
Search time becomes O n instead of O log n.
1. Given the root of a binary tree, Design an algorithm that returns a list containing the values of all nodes visited in preorder traversal order, which follows the sequence: Root -> Left -> Right.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | A perfectly balanced binary tree | A completely skewed binary tree | An empty tree (null root) |
Output | Preorder list with all nodes | Preorder list with all nodes | Empty list [] |
Explanation | Balanced tree has minimal depth → less recursion stack | Skewed tree behaves like a linked list → max depth | No nodes to visit → return empty list |
2. Given the root of a binary tree. Design an algorithm that will return the inorder traversal of its nodes values.
Inorder traversal follows the pattern: Left -> Root -> Right.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Best case | Worst case | Edge case |
---|---|---|---|
input | Perfectly balanced binary tree | Skewed tree (all nodes on one side) | Null input / single node tree |
output | Nodes visited in left-root-right order | Nodes visited linearly (still left-root-right) | Empty list or root value only |
explanation | Left and right subtrees equally deep | Recursion stack grows to height n | Nothing to traverse / trivial case |
3. Given a binary tree. Design an algorithm that returns the values of its nodes in postorder traversal order (Left -> Right -> Root).
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Best case | Worst case | Edge case |
---|---|---|---|
input | Balanced binary tree with minimal height | Skewed binary tree (e.g., linked-list-like, all left) | Tree is null or has only one node |
output | Valid postorder list (e.g., [left, right, root]) | Correct list with all nodes in postorder | Empty list ([]) or list with single element |
explanation | Recursive stack depth is minimal (log n), traversal visits nodes L → R → Root | Traversal must recurse through n levels (linear depth) | Tree has no children or root is null, yet traversal is valid |
4. Given the root of a binary tree. Design an algorithm that returns the values of its nodes level by level (breadth-first traversal), from top to bottom, left to right.
Return a 2D array where each subarray contains the node values at that specific level.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | Perfect binary tree (e.g., complete and balanced) | Skewed binary tree (all left or all right) | Empty tree (root = null) or single-node tree |
Output | E.g., [[1], [2, 3], [4, 5, 6, 7]] | E.g., [[1], [2], [3], [4]] | Empty array [] or [[1]] |
Explanation | All nodes fill each level left-to-right fully | Each level has only one node (degenerated tree) | No nodes or only root node — edge conditions |
5. Given a binary tree. Design an algorithm that returns the height of the tree.
A binary tree height is the number of levels it contains, where the root is at level 1 and height is the total number of levels from the root to the deepest leaf node.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | Perfect binary tree of height h | Skewed tree (like a linked list) | Empty tree (root = null) |
Output | h | n (where n is total number of nodes) | 0 |
Explanation | Tree is completely balanced; all levels are fully populated | Tree has only left or only right children, forming a straight line | No nodes exist, so height is 0 |
6. Given the root of a binary tree. Design an algorithm that determines if the tree is a valid Binary Search Tree(BST).
A valid BST is defined as:
Return true if it is a valid BST, otherwise return false.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | Balanced BST like: 5 → 3, 7 → 2, 4, 6, 8 | Skewed or deep BST with one wrong node deep | null, or a single node tree |
Output | true | false | true |
Explanation | All nodes follow BST rule | Violates condition in deep subtree | An empty or single-node tree is a valid BST |
7. Given the root of a binary tree. Design an algorithm that will return the total number of nodes in the binary tree.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | Perfect Binary Tree: 1→2,3; 2→4,5 | Skewed Tree: 1 → 2 → 3 → 4 → 5 (linked list) | null or 1 with no children |
Output | 5 | 5 | 0 for null 1 for single-node tree |
Explanation | All nodes are present and balanced | Still counts all nodes despite imbalance | Return 0 if tree is empty, or count root as |
8. Given the root of a Binary Tree. Design an algorithm that returns the total number of leaf nodes in the tree.
A leaf node is a node with no children - both its left and right pointers are null.
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | level order traversal: 1 2 3 4 5 6 7 | ``` | Single node: 1 |
Output | 4 (leaf nodes: 4, 5, 6, 7) | 1 (only node 4 is a leaf) | 0 (null), 1 (only root is a leaf) |
Explanation | All nodes at the last level are leaves | Only the deepest node has no children | Empty = no nodes; single node with no children is a leaf |
9. Given the root node of a binary tree. Design an algorithm that return the level order traversal in spriral (zigzag) form.
Return a 2D array where each subarray contains node values for the level.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case (Perfect Binary Tree) | Worst Case (Skewed Tree) | Edge Case (Empty Tree) |
---|---|---|---|
Parameters | Complete tree (e.g., depth = 3) | All nodes in left/right chain | root = null |
Output | [[1], [3, 2], [4, 5, 6, 7]] | [[1], [2], [3], [4]] | [] |
Explanation | All levels have balanced children and direction alternates | Single-node path means direction flips each level but only one node per level | Empty tree returns empty result |
10. Design an algorithm to invert a binary tree such that the tree becomes a mirror image of itself.
For every node its left and right children must be swapped.
Return the root node of the mirrored tree.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | A single node tree | A completely unbalanced (skewed) tree | Null / empty tree (root = null) |
Output | The same single node | A mirrored version of the skewed structure | null |
Explanation | Nothing to swap, return as-is | All left nodes become right, and vice versa | Handles empty input gracefully |
11. Given the roots of two binary trees. Design an algorithm that checks if they are structurally identical and nodes have the same value.
Return true if the trees are identical, otherwise return false.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Best case | Worst case | Edge case |
---|---|---|---|
input | root1 = null, root2 = null | Two full binary trees with completely different structure or values | One tree is null, the other is a valid non-empty tree |
output | true | false | false |
explanation | Both trees are empty, so they are structurally and value-wise identical | The algorithm must visit every node to determine they differ | The trees can't be identical if one is empty and the other is not |
12. Given the root of a binary tree. Design an algorithm that return the length (number of edges) of the longest path between any two nodes in the tree.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | Only the root node (no children) | Skewed tree with all nodes on one side or a full balanced binary tree | A tree with only 2 nodes (root and one child) |
Output | 0 | n - 1 where n is number of nodes | 1 |
Explanation | No path exists between two distinct nodes | Longest path spans from the deepest leaf in left subtree to right | One edge connects two nodes, hence diameter = 1 |
13. Given the root of a binary tree and two distinct nodes p and q. Design an algorithm that return their lowest common ancestor (LCA).
The Lowest Common Ancestor of two nodes p and q in a binary tree is defined as the deepest node (i.e., farthest from the root) that is an ancestor of both p and q.
Note: A node can be a descendant of itself according to the definition of ancestor.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter \ Case | Worst Case | Worst Case | Edge Case |
---|---|---|---|
Input | p and q are direct children of root | Tree is skewed (like a linked list) and p, q are at opposite ends | One node is an ancestor of the other |
Output | Root node | Root or deep common node | Ancestor node itself |
Explanation | LCA found immediately at root with minimal traversal | Must search deep on both left and right subtrees | The ancestor node is returned as LCA (since a node can be ancestor of itself |
1. Given two integer arrays:
Both arrays contain unique elements and represent the traversal of a valid binary tree.
Design an algorithm to construct the binary tree and return its root node.
You may assume that the tree contains no duplicate values.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Balanced binary tree | Completely skewed binary tree (like a linked list) | Single-node tree or empty input |
Output | Balanced tree with optimal recursion depth | Deep recursion with n depth due to imbalance | Tree with one node or null |
Explanation | Tree is built with minimal stack overhead | Maximum recursion required, due to one-sided branches | Ensures base case handling |
2. Given Two integer arrays:
Both arrays contain unique elements, and the tree is guaranteed to be valid.
Design an algorithm that constructs the binary tree and returns the root node of the tree.
You may assume that the tree contains no duplicate values.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] | inorder = [1,2,3,4,5], postorder = [1,2,3,4,5] (skewed tree) | inorder = [1], postorder = [1] |
Output | Root of a balanced binary tree | Root of a skewed (degenerate) tree (like linked list) | Root node with value 1 |
Explanation | Balanced tree is built with recursive splits on both sides | Each recursive call creates only one right child | Base case triggers immediately; one-node tree |
Serialization is the process of converting a binary tree into a string representation that can be easily stored or transmitted.
Deserializing is the inverse process, where the string is used to reconstruct the original binary tree.
3. Design an algorithm that implement the following two functions:
The algorithm should:
Assume all node values are integers and the binary tree does not contain cycles.
Binary Tree Node:
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Perfectly balanced (e.g. complete binary) | Highly skewed tree (e.g. linked-list-shaped) | Empty tree or single node (null or just root) |
Output | "1,2,3,#,#,4,5,#,#,#,#" | "1,#,2,#,3,#,4,#,5,#,#" | "#" or "1,#,#" |
Explanation | Efficiently encodes/decodes levels | Deep recursion or queue traversal still accurate | Handles minimal or missing data correctly |
4. Given the root of a binary tree. Design an algorithm that determine whether the tree is height-balanced.
A binary tree is height-balanced if, for every node in the tree, the absolute difference between the heights of the left and right subtrees is no more than 1, and both subtrees are also height-balanced.
Return: true if the tree is height-balanced, otherwise return false.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | root = null | Skewed tree (every node has one child) | Tree with just 1 node |
Output | true | false | true |
Explanation | Empty tree is balanced | Left-heavy tree causes imbalance | A single node has no imbalance |
5. Given the root of a binary tree where each node contains an integer value (positive, negative, or zero).
A path is defined as any sequence of connected nodes in the tree where:
The sum of a path is the sum of the values of the nodes in that path.
Design an algorithm that computes the maximum path sum and return the maximum sum of values along any valid path.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | [1, 2, 3] | [-10, -20, -30] | [5] |
Output | 6 (2 → 1 → 3) | -10 (only node with max value) | 5 |
Explanation | The path from left → root → right gives max | Must pick least negative node | One node is the only valid path |
6. Given the root of a binary tree where each node contains an integer value, and an integer targetSum.
Design an algorithm that finds all root-to-leaf path in the tree such that the sum of the node values in each path equals targetSum.
A root-to-leaf path is defined as a path starting from the root node and ending at a leaf node (i.e., a node with no children).
Return a list of all valid paths, where each path is represented as a list of integers.
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | [1, 2, null] targetSum = 3 | [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1] targetSum = 22 | [] or [1, 2, 3] with targetSum = 100 |
Output | [[1, 2]] | [[5,4,11,2], [5,8,4,5]] | [] |
Explanation | Only one path from root to leaf adds up | Multiple paths require deep DFS + sum tracking | Either tree is null or paths don’t sum up |
7. Given a root of a binary tree. Design an algorithms that returns the boundary raversal of the tree in anti-clockwise order, starting from the root.
The boundary includes three parts:
Return a list of node values representing the boundary traversal in the specified order.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Perfect balanced binary tree | Skewed tree with many nodes | Single-node tree or tree with only one branch |
Output | Balanced traversal of all sections | Long traversal with left, leaf, and right nodes | Only root or only leaves |
Explanation | Easy to collect left, leaves, right | Traversal covers deep trees with many nodes | Tests minimal input, edge behavior |
8. Given the root of a binary tree. Design an algorithm that returns the vertical order traversal of its nodes values.
For vertical traversal:
Return a list of lists, where each sublist represents a vertical level from leftmost to rightmost.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Complete or balanced binary tree | Highly skewed tree (like a linked list) | Null tree or single node |
Output | Even distribution across HD levels | All nodes fall in separate or same columns | Empty list or single-column list |
Explanation | Traversal follows BFS + HD group logic | Needs BFS + depth tracking and proper ordering | Verifies boundary and root logic |
9. Given the root of a Binary Search Tree and an integer key. Design an algorithms to delete the node with the given key in the BST while preserving the BST properties.
Return the root node of the updated BST after deletion.
BST Properties to Preserve:
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Node is a leaf | Node has two children with deep subtrees | Tree is empty or node doesn't exist |
Output | Simple removal | Node replaced with in-order successor/predecessor | Same tree or null root |
Explanation | O(log n) delete in balanced tree | Traversal + restructure (O(h) height of tree) | No-op or full removal of the tree |
10. Given the root of a binary search tree (BST) and an integer k. Design an algorithm to find and return the kth smallest element in the BST.
The BST contains unique values and follows the standard properties:
1 ≤ k ≤ total number of nodes in the tree.
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Balanced BST, k = 1 k = 1, root: [3,1,4,null,2] | Skewed BST (like a linked list) k = n, skewed BST: [1,null,2,null,3,...] | Tree with only one node k = 1, root: [7] |
Output | Returns leftmost node (smallest value) | Traverses all nodes to reach kth smallest | Returns the only node in the tree |
Explanation | Answer is found early in left subtree | Requires full traversal to find kth element | Verifies that algorithm handles minimal tree |
11. Given the root of a Binary Search Tree(BST) and two nodes p and q (existing in the tree). Design an algorithm to find and return their lowest common ancestor (LCA).
The Lowest Common Ancestor of two nodes p and q in a BST is defined as the lowest(i.e., deepest) node in the tree that has both p and q as decendants (where a node can be a descendant of itself).
Parameter\ Case | Best Case | Worst Case | Edge Case |
---|---|---|---|
Parameters | Balanced BST, LCA is root | Skewed BST, LCA near root | p is ancestor of q or vice versa |
Output | LCA at root | Deep recursion or traversal | Return the ancestor node itself |
Explanation | Quick resolution due to BST properties | Needs full traversal due to depth | Algorithm must account for LCA being one of the nodes |