Tree Node Levels and Balance
NetflixOnsiteMedium
A binary tree node is a list [value, left, right], where left and right are nodes or None. You are given the root node of a binary tree.
Part 1: Levels and balance records
Return one record [value, level, balanced] for every node of the tree, in preorder: a node, then its left subtree, then its right subtree.
The root is at level 0, and each child is one level below its parent. balanced is True when the heights of the node's left and right subtrees differ by at most 1. An empty subtree has height 0.
- Example 1
- root
[1,[2,[4,null,null],[5,null,null]],[3,null,null]]- Output
[[1,0,true],[2,1,true],[4,2,true],[5,2,true],[3,1,true]]
Why: Records follow preorder: 1, 2, 4, 5, 3, with levels 0, 1, 2, 2, 1. Every node's left and right subtree heights differ by at most 1, so each record ends in
True.
Constraints
1 <= number of nodes <= 10^4- The tree is at most
500levels deep 1 <= value <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.