Tree

Tree

Traversal:

Pre-order traversal

public void preorder(TreeNode root) {
    if (root == null) {
        return;
    }
    // process the node
    // ...
    preorder(root.left);
    preorder(root.right);
}

public List<Integer> preorderTraverse(TreeNode root) {
  List<Integer> result = new ArrayList<>();
  if (root == null) {
     return result;
  }
  Stack<TreeNode> stack = new Stack<>();
  stack.push(root);
  while (!stack.isEmpty()) {
     TreeNode curNode = stack.pop();
     result.add(curNode.val);
     if (curNode.right != null) {
        stack.push(curNode.right);
     }
     if (curNode.left != null) {
        stack.push(curNode.left);
     }
  }
  return result;
}

In-order traversal

Post-order traversal

Level-order traversal (BFS)

Zigzag traversal

Depth-first search (DFS)

Finding the minimum/maximum value in a binary search tree (BST)

Checking if two trees are identical or not

Find all ancestors for a node

Find items in BST

Finding the diameter of a binary tree (the length of the longest path between any two nodes)

Checking if a given tree is balanced or not (height-balanced or weight-balanced)

Calculating the sum of all nodes in a binary tree:

Calculating the height of a binary tree:

Breadth-first search (BFS)

Finding the shortest path between two nodes

Counting the number of nodes at a given level

Finding the depth/height of a node in a binary tree

Checking if a binary tree is a complete binary tree

Finding the minimum depth of a binary tree

Construction:

Build tree from pre-order and in-order traversal

Build tree from post-order and in-order traversal

Build tree from level-order traversal

Convert binary tree to linked list

Convert binary tree to doubly linked list

Modification:

Invert binary tree

Mirror binary tree

Flatten binary tree

Trim binary search tree

Delete node from binary search tree

Validation:

Checking if a given binary tree is a BST

Validate balanced binary tree

Miscellaneous:

Finding the depth of a tree

Minimum depth of binary tree

Maximum path sum of binary tree

Count complete tree nodes

Serialize and deserialize binary tree

Lowest common ancestor of a binary tree

Lowest common ancestor of BST

Finding the shortest path between two nodes

DFS solution

BFS solution

Last updated