Ensuring All Tree Leaves Reside at the Same Level
isLeafAtSameLevel:
The cornerstone of today's exploration, this function initiates a depth-first search (DFS) that dives deep into each branch of the tree, marking the level of the first encountered leaf. As it progresses, it compares the level of subsequent leaves, ensuring uniformity across all leaf nodes. This comparison is crucial, as it validates the consistency of the tree's structure, affirming that all leaves indeed share the same depth. A flag, leafLevel, is ingeniously used to track the level of the first leaf encountered, serving as a benchmark for all comparisons.
1function isLeafAtSameLevel(root) {
2  let leafLevel = -1;
3
4  function dfs(node, level) {
5    if (!node) return true;
6    if (!node.left && !node.right) {
7      if (leafLevel === -1) {
8        leafLevel = level;
9        return true;
10      }
11      return level === leafLevel;
12    }
13
14    return dfs(node.left, level + 1) && dfs(node.right, level + 1);
15  }
16
17  return dfs(root, 0);
18}
19
20function TreeNode(val, left, right) {
21  this.val = val === undefined ? 0 : val;
22  this.left = left === undefined ? null : left;
23  this.right = right === undefined ? null : right;
24}
25
26let root1 = new TreeNode(1);
27root1.left = new TreeNode(2);
28root1.right = new TreeNode(3);
29
30console.log(isLeafAtSameLevel(root1));
31
32let root2 = new TreeNode(1);
33root2.left = new TreeNode(2);
34root2.right = new TreeNode(3);
35root2.left.left = new TreeNode(4);
36
37console.log(isLeafAtSameLevel(root2));
38
39// Example 3
40let root3 = new TreeNode(1);
41root3.left = new TreeNode(2);
42root3.right = new TreeNode(3);
43root3.left.right = new TreeNode(4);
44root3.right.right = new TreeNode(5);
45
46console.log(isLeafAtSameLevel(root3));
47