Trees

- Fundamentals -

Core Tree Terminologies

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

PropertyDescription
AcyclicA tree has no cycles
ConnectedThere is a path between any two nodes
RootedOne node is called the root (typically at the top)
N - 1 edgesA tree with N nodes always has exactly N - 1 edges
Unique pathsThere 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.

ABCDEF--- Root (Depth = 0)--- Internal nodes (Depth = 1)--- Leaf Nodes (Depth = 2)Height of tree = 2Degree of node B = 2 (D, E)Degree of node A = 2 (B, C)

Types of Trees

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

  • Maximum nodes at level ; L 2 ^l (o-based indexing)
  • Maximum nodes in a binary tree of height h : 2 ^(h+1) - 1
ABC

2. Binary Search Tree (BST): A special type of binary tree that maintains a sorted order.

  • All nodes in the left subtree have values less than the node.
  • All nodes in the right subtree have values greater than the node.

Supports efficient searching, insertion, and deletion in O log n average time if balanced.

Properties

  • In order traversal yields sorted data
  • Worst case time complexity O n (if unbalanced, e.g., skewed tree)
10515

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

  • Children are usually stored in a list or array.
  • Not inherently sorted unless designed that way.
ABDC

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:

  • AVL Tree: Strictly balanced using height checks and rotations.
  • Red-Black Tree: Loosely balanced using color and rotation rules.
  • B-Trees/ B+ Trees: Used in databases and file systems.
4261357

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.

1234

Preorder Traversal

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 CaseEdge 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

Inorder Traversal

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 caseEdge case
input Perfectly balanced binary tree  Skewed tree (all nodes on one side) Null input / single node tree
outputNodes visited in left-root-right order Nodes visited linearly (still left-root-right) Empty list or root value only
explanationLeft and right subtrees equally deep Recursion stack grows to height n Nothing to traverse / trivial case

Postorder Traversal

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 caseEdge 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
outputValid postorder list (e.g., [left, right, root]) Correct list with all nodes in postorder Empty list ([]) or list with single element
explanationRecursive 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

Level Order Traversal

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;
  }
}

1234567[1],[2, 3],[4, 5, 6][]
Parameter \ Case Worst CaseWorst CaseEdge 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
OutputE.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

Depth of Tree

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;
    }
  }

1234Maximum Depth = 31 - 2 - 4
Parameter \ Case Worst CaseWorst CaseEdge Case
Input Perfect binary tree of height h Skewed tree (like a linked list)
Empty tree (root = null)
Outputh 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

Is it a BST?

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:

  • The left subtree of a node contains only nodes with values less than the nodes value.
  • The right subtree of a node contains only nodes with values greater than the nodes value.
  • Both the left and right subtrees must also be valid BSTs.

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;
    }
  }

537248532687 Valid BSTInvalid BST6 1
Parameter \ Case Worst CaseWorst CaseEdge 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
Outputtrue false true
Explanation All nodes follow BST rule Violates condition in deep subtree An empty or single-node tree is a valid BST

Size of the Binary Tree

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 CaseWorst CaseEdge 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
Output5 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 

Count Leaf Nodes

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 CaseWorst CaseEdge Case
Input level order traversal: 1 2 3 4 5 6 7```
Single node: 1
Output4 (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 leavesOnly the deepest node has no childrenEmpty = no nodes; single node with no children is a leaf

Spiral Level Traversal

9. Given the root node of a binary tree. Design an algorithm that return the level order traversal in spriral (zigzag) form.

  • Start from the root at level 0.
  • Traverse left to right on even-numbered levels.
  • Traverse right to left on odd-numbered levels.

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;
    }
  }

123764 [5 [1],[3, 2],[7, 6, 5, 4]]Spiral Output:
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 alternatesSingle-node path means direction flips each level but only one node per levelEmpty tree returns empty result

Mirror Binary Tree

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;
    }
  }

12332 1
Parameter\ Case Best CaseWorst CaseEdge Case
Parameters A single node tree A completely unbalanced (skewed) tree
Null / empty tree (root = null)
OutputThe same single nodeA mirrored version of the skewed structurenull
Explanation Nothing to swap, return as-isAll left nodes become right, and vice versaHandles empty input gracefully

Identical Binary Trees

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 caseEdge 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
outputtrue false false
explanationBoth 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

Diameter of a Binary tree

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;
    }
  }

12345 Longest path = [ 4 - 2 - 1 - 3 ] = 3 edges Diameter = 3
Parameter \ Case Worst CaseWorst CaseEdge 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)
Output0 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

Lowest Common Ancestor

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;
    }
  }

35162 LCA (7, 4) = 2 LCA (6, 4) = 50874LCA (6, 8) = 3LCA (5, 4) = 5
Parameter \ Case Worst CaseWorst CaseEdge 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
OutputRoot 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

- Intermediate Problems -

Construct Binary Tree 1

1. Given two integer arrays:

  • preorder[] which represents the preorder traversal of a binary tree (Root -> Left -> Right)
  • inorder[] which represents the inorder traversal of the same binary tree (Left -> Root -> Right)

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 CaseWorst CaseEdge Case
Parameters Balanced binary tree Completely skewed binary tree (like a linked list)
Single-node tree or empty input
OutputBalanced tree with optimal recursion depthDeep recursion with n depth due to imbalanceTree with one node or null
Explanation Tree is built with minimal stack overheadMaximum recursion required, due to one-sided branchesEnsures base case handling

Construct Binary Tree 2

2. Given Two integer arrays:

  • postorder[] represents the postorder traversal of a binary tree (Left -> Right -> Root)
  • inorder[] represents the inorder traversal of the same binary tree (Left -> Root -> Right)

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 CaseWorst CaseEdge 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]
OutputRoot of a balanced binary treeRoot of a skewed (degenerate) tree (like linked list)Root node with value 1
Explanation Balanced tree is built with recursive splits on both sidesEach recursive call creates only one right childBase case triggers immediately; one-node tree

Serializing Deserializing 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:

  • serialize(root) - Encodes a tree to a single string.
  • deserialization - is the inverse process, where the string is used to reconstruct the original binary tree.

The algorithm should:

  • Preserve Structure and Values: The serialized string must retain the exact structure and values of the original tree.
  • Handle null (missing) children which is represented as '#' correctly.
  • Work for large and skewed trees efficiently.

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 CaseWorst CaseEdge 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 levelsDeep recursion or queue traversal still accurateHandles minimal or missing data correctly

Is Binary Tree Balanced?

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;
      }
    }
   
Unbalanced Binary Tree5321Balanced Binary Tree5381410
Parameter\ Case Best CaseWorst CaseEdge 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

Path with Maximum Sum

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:

  • Each pair of adjacent nodes is connected by a parent-child link.
  • Each node in the path appears only once.
  • The path can start and end at any node in the tree.

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 CaseWorst CaseEdge 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

Root to Leaf Path Sum Finder

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 CaseWorst CaseEdge 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

Boundary Traversal of a Binary Tree

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:

  • Left Boundary - all the nodes on the left edge, excluding leaf nodes.
  • Leaf nodes - all the leaf nodes (from left to right).
  • Right Boundary - all the nodes on the right edge, excluding leaf nodes, collected in reverse order.

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;
    }
  }
     
123456789Traversal Order1 - 2 - 4- 8 - 9 - 6 - 7 - 3
Parameter\ Case Best CaseWorst CaseEdge Case
Parameters Perfect balanced binary treeSkewed tree with many nodesSingle-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

Vertical Order Traversal

8. Given the root of a binary tree. Design an algorithm that returns the vertical order traversal of its nodes values.

For vertical traversal:

  • Each node is assigned a horizontal distance (HD) from the root. The root has HD = 0. Left child has HD-1, and right child has HD + 1.
  • Nodes are grouped by their horizontal distance (HD) from the root.
  • Within the same column, nodes are ordered top-to-bottom by depth (level).
  • If multiple nodes share the same column and depth, they should appear in left-to-right order, i.e., as encountered in a level-order (BFS) 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;
    }
  }
     
3984017[493, 0, 187]
Parameter\ Case Best CaseWorst CaseEdge Case
Parameters Complete or balanced binary treeHighly 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

Delete a Node in BST

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:

  • The left subtree of a node contains only nodes with values less than the node's value.
  • The right subtree of a node contains only nodes with values greater than the node's value.
  • Both left and right subtrees must also be BSTs.
Parameter\ Case Best CaseWorst CaseEdge Case
Parameters Node is a leafNode has two children with deep subtreesTree 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

Kth Smallest Element in BST

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:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.

1 ≤ k ≤ total number of nodes in the tree.

Parameter\ Case Best CaseWorst CaseEdge 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

LCA in BST

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).

  • All node values in the BST are unique.
  • Both nodes p and q are guaranteed to exist in the tree.
Parameter\ Case Best CaseWorst CaseEdge 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