An arbitrary binary tree may still contain well-ordered parts. Take any node together with every node below it and call that a branch (a subtree). A branch is well ordered when it is a valid binary search tree with strict ordering: every value in a node's left part is smaller than the node and every value in its right part is larger. Return the number of nodes in the largest well-ordered branch, or 0 for an empty tree.
Examples
20
/ \
9 25
/ \ / \
4 12 22 30
/ \
10 21
Input: root = build_tree([20, 9, 25, 4, 12, 22, 30, None, None, 10, 21])
Output: 5 (the subtree rooted at 9; 21 sits left of 20 but is larger, so the whole tree fails)
3
/ \
2 4
/
1
Input: root = build_tree([3, 2, 4, None, None, 1])
Output: 2 (4 with its left child 1; the whole tree fails because 1 < 3 sits on the right)
Constraints
0 <= number of nodes <= 3000- Values are integers (repeats possible; a repeat anywhere inside a subtree makes it invalid)
- O(n) time
Goals
- Combine child summaries (valid, size, min, max) in one postorder pass
- Treat a subtree as a node together with all of its descendants