Next Leaf in an Ordered Tree
Updated
Problem statement
Given an ordered rooted tree children and one of its leaves leaf, return the leaf that comes right after leaf in a depth-first traversal.
Nodes are numbered from 0 to children.length - 1, and node 0 is the root. children[u] lists the children of node u from left to right. The traversal visits children in that order and finishes each child's whole subtree before moving to the next child. A node with no children is a leaf.
Return -1 if leaf is the last leaf. The input is always one valid connected tree, and leaf is an existing leaf.
Function
nextLeaf(children: int[][], leaf: int) → intExamples
Example 1
children = [[1,2],[3,4],[],[],[]]leaf = 4return = 2The leaf order is [3,4,2], so leaf 2 follows leaf 4.
Example 2
children = [[1,2],[3,4],[],[],[]]leaf = 2return = -1Leaf 2 is the last leaf, so no leaf comes after it.
Example 3
children = [[]]leaf = 0return = -1The root is the only leaf, so no leaf comes after it.
Constraints
1 <= children.length <= 10^5.- Every child ID is a valid node ID.
- Each non-root node has one parent, and the tree has no cycles.
leafnames a node whose child list is empty.
More Apple Phone Screen questions
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Dec 2026
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Evaluate DivisionPHONE SCREEN · Seen Nov 2026
- Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
- Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
- Design a Food Rating SystemPHONE SCREEN · Seen Oct 2026
- Days Until Poisoned Plants StabilizePHONE SCREEN · Seen Oct 2026
- Capture Surrounded Regions with Union-FindPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Find File Paths in a Directory TreeUber · PHONE SCREENUber interview questions
- Delete a Filesystem TreeDatadog · PHONE SCREEN · ONSITE INTERVIEWDatadog interview questions
- Turn a BST Into a Sorted Doubly Linked ListAdobe · PHONE SCREENAdobe interview questions
- Kth Smallest Value in a BSTExpedia · PHONE SCREEN · ONSITE INTERVIEWExpedia interview questions
- Kth Smallest Element in a BSTNutanix · PHONE SCREENNutanix interview questions
- Recover a Tree From Preorder TraversalGrammarly · PHONE SCREEN · ONSITE INTERVIEW
- Serialize and Deserialize a Binary TreeNVIDIA · PHONE SCREENNVIDIA interview questions
- Binary Tree Preorder TraversalMorgan Stanley · PHONE SCREENMorgan Stanley interview questions
- Binary Tree Inorder TraversalBloomberg LP · PHONE SCREENBloomberg LP interview questions
- Recover a Tree from Preorder Depth EncodingSuperhuman · PHONE SCREENSuperhuman interview questions