← 返回 netflix 的题目列表DFS: Print Each Node's Level and Whether It Is Balanced
类型:online_judge
Problem: DFS — Print Each Node’s Level and Whether It Is a Balanced Node
Given a tree rooted at root (typically a binary tree; for an N-ary tree follow the interviewer’s definition), traverse the tree and output for each node:
level: the node’s depth/level (root is level 0)
isBalanced: whether the node is a balanced node
A node is balanced if the height difference between its left and right subtree is at most 1, i.e. abs(height(left) - height(right)) <= 1, with an empty subtree having height 0.
Output format
Print one line per node:
<node_value> <level> <isBalanced>
Use true/false for isBalanced.
Constraints
Number of nodes N: 1 to 2 * 10^5
Target overall time complexity O(N); avoid recomputing heights per node (O(N^2)).
Test cases (binary tree represented as level-order array; null means missing)
input:
[3,9,20,null,null,15,7]
output:
3 0 true
9 1 true
20 1 true
15 2 true
7 2 true
input:
[1,2,2,3,3,null,null,4,4]
output:
1 0 false
2 1 false
2 1 true
3 2 false
3 2 true
4 3 true
4 3 true
input:
[1]
output:
1 0 true
input:
[1,2,null,3]
output:
1 0 false
2 1 false
3 2 true
input:
[1,2,3,4,5,6,7]
output:
1 0 true
2 1 true
3 1 true
4 2 true
5 2 true
6 2 true
7 2 true
Example
Input
[3,9,20,null,null,15,7]
Output
3 0 true
9 1 true
20 1 true
15 2 true
7 2 true