FastPrepCheck Whether All Leaves Are at the Same Level
Problem · Tree

Check Whether All Leaves Are at the Same Level

Learn this problem
EasyAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given the root of a nonempty binary tree, return whether every leaf is at the same depth.

A leaf has no left or right child. The root has depth 0, although only equality of leaf depths affects the result.

Function

leavesAtSameLevel(root: TreeNode) → boolean

Examples

Example 1

root = [1,2,3,4,5,6,7]return = true

All four leaves occur two edges below the root.

Example 2

root = [1,2,3,4,null,null,null,8]return = false

Node 3 is a leaf at depth one, while node 8 is at depth three.

Example 3

root = [1,2,3,null,4,5,null]return = true

Leaves 4 and 5 both occur at depth two despite different child directions.

Constraints

  • The tree contains between 1 and 100000 nodes.
  • -10^9 <= node.val <= 10^9.

More Amazon problems

drafts saved locally
public boolean leavesAtSameLevel(TreeNode root) {
  // write your code here
}
root[1,2,3,4,5,6,7]
expectedtrue
checking account