Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Build confidence with an intuition-first walkthrough focused on tree fundamentals.
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:
Example 1:
Input: root = [1,null,2,2] Output: [2]
Example 2:
Input: root = [0] Output: [0]
Constraints:
[1, 104].-105 <= Node.val <= 105Problem summary: Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it. If the tree has more than one mode, return them in any order. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[1,null,2,2]
[0]
validate-binary-search-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #501: Find Mode in Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int mx;
private int cnt;
private TreeNode prev;
private List<Integer> res;
public int[] findMode(TreeNode root) {
res = new ArrayList<>();
dfs(root);
int[] ans = new int[res.size()];
for (int i = 0; i < res.size(); ++i) {
ans[i] = res.get(i);
}
return ans;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
cnt = prev != null && prev.val == root.val ? cnt + 1 : 1;
if (cnt > mx) {
res = new ArrayList<>(Arrays.asList(root.val));
mx = cnt;
} else if (cnt == mx) {
res.add(root.val);
}
prev = root;
dfs(root.right);
}
}
// Accepted solution for LeetCode #501: Find Mode in Binary Search Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
mx, cnt := 0, 0
var prev *TreeNode
var ans []int
var dfs func(root *TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
dfs(root.Left)
if prev != nil && prev.Val == root.Val {
cnt++
} else {
cnt = 1
}
if cnt > mx {
ans = []int{root.Val}
mx = cnt
} else if cnt == mx {
ans = append(ans, root.Val)
}
prev = root
dfs(root.Right)
}
dfs(root)
return ans
}
# Accepted solution for LeetCode #501: Find Mode in Binary Search Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
def dfs(root):
if root is None:
return
nonlocal mx, prev, ans, cnt
dfs(root.left)
cnt = cnt + 1 if prev == root.val else 1
if cnt > mx:
ans = [root.val]
mx = cnt
elif cnt == mx:
ans.append(root.val)
prev = root.val
dfs(root.right)
prev = None
mx = cnt = 0
ans = []
dfs(root)
return ans
// Accepted solution for LeetCode #501: Find Mode in Binary Search Tree
struct Solution;
use rustgym_util::*;
trait Inorder {
fn inorder(&self, prev: &mut Option<i32>, count: &mut usize, f: &mut impl FnMut(i32, usize));
}
impl Inorder for TreeLink {
fn inorder(&self, prev: &mut Option<i32>, count: &mut usize, f: &mut impl FnMut(i32, usize)) {
if let Some(node) = self {
let node = node.borrow();
Self::inorder(&node.left, prev, count, f);
if let Some(prev_val) = prev.as_mut() {
if *prev_val == node.val {
*count += 1;
} else {
*count = 1;
*prev = Some(node.val);
}
} else {
*prev = Some(node.val);
*count = 1;
}
f(node.val, *count);
Self::inorder(&node.right, prev, count, f);
}
}
}
impl Solution {
fn find_mode(root: TreeLink) -> Vec<i32> {
let mut max = 0;
let mut count = 0;
let mut prev: Option<i32> = None;
let mut modes: Vec<i32> = vec![];
root.inorder(&mut prev, &mut count, &mut |_, count| {
max = usize::max(count, max);
});
prev = None;
count = 0;
root.inorder(&mut prev, &mut count, &mut |val, count| {
if count == max {
modes.push(val);
}
});
modes
}
}
#[test]
fn test() {
let root = tree!(1, None, tree!(2, tree!(2), None));
assert_eq!(Solution::find_mode(root), vec![2]);
}
// Accepted solution for LeetCode #501: Find Mode in Binary Search Tree
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #501: Find Mode in Binary Search Tree
// /**
// * Definition for a binary tree node.
// * public class TreeNode {
// * int val;
// * TreeNode left;
// * TreeNode right;
// * TreeNode() {}
// * TreeNode(int val) { this.val = val; }
// * TreeNode(int val, TreeNode left, TreeNode right) {
// * this.val = val;
// * this.left = left;
// * this.right = right;
// * }
// * }
// */
// class Solution {
// private int mx;
// private int cnt;
// private TreeNode prev;
// private List<Integer> res;
//
// public int[] findMode(TreeNode root) {
// res = new ArrayList<>();
// dfs(root);
// int[] ans = new int[res.size()];
// for (int i = 0; i < res.size(); ++i) {
// ans[i] = res.get(i);
// }
// return ans;
// }
//
// private void dfs(TreeNode root) {
// if (root == null) {
// return;
// }
// dfs(root.left);
// cnt = prev != null && prev.val == root.val ? cnt + 1 : 1;
// if (cnt > mx) {
// res = new ArrayList<>(Arrays.asList(root.val));
// mx = cnt;
// } else if (cnt == mx) {
// res.add(root.val);
// }
// prev = root;
// dfs(root.right);
// }
// }
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.