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.
1functionisLeafAtSameLevel(root) {
2let leafLevel = -1;
34functiondfs(node, level) {
5if (!node) returntrue;
6if (!node.left && !node.right) {
7if (leafLevel === -1) {
8 leafLevel = level;
9returntrue;
10 }
11return level === leafLevel;
12 }
1314return dfs(node.left, level + 1) && dfs(node.right, level + 1);
15 }
1617return dfs(root, 0);
18}
1920functionTreeNode(val, left, right) {
21this.val = val === undefined ? 0 : val;
22this.left = left === undefined ? null : left;
23this.right = right === undefined ? null : right;
24}
2526let root1 = new TreeNode(1);
27root1.left = new TreeNode(2);
28root1.right = new TreeNode(3);
2930console.log(isLeafAtSameLevel(root1));
3132let root2 = new TreeNode(1);
33root2.left = new TreeNode(2);
34root2.right = new TreeNode(3);
35root2.left.left = new TreeNode(4);
3637console.log(isLeafAtSameLevel(root2));
3839// Example 340let 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);
4546console.log(isLeafAtSameLevel(root3));
47