Example 1
- Input
- root = [2,1,3]
- Output
- true
The left subtree contains only 1, which is below 2; the right contains only 3, which is above 2. Both children are leaves.
Given the root of a binary tree, determine whether it is a valid binary search tree, where every node in the left subtree is smaller and every node in the right subtree is larger than the node. The rule must hold for every descendant, not just the immediate children.
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST requires that the left subtree of a node contains only nodes with values less than the node's value, and the right subtree contains only nodes with values greater than the node's value. Both the left and right subtrees must also be valid binary search trees, and duplicate values are not allowed.
[1, 10^4].-2^31 <= Node.val <= 2^31 - 1The left subtree contains only 1, which is below 2; the right contains only 3, which is above 2. Both children are leaves.
A singleton has no ordering conflicts. The minimum signed 32-bit value is legal and must not collide with an artificial initial bound.
Every immediate child comparison passes, including 4 being left of 7. But 4 is also in the right subtree of 5, where all values must exceed 5.
A node must satisfy every ancestor, not only its parent. In Example 1, 1 belongs below 2 and 3 belongs above it. You can either inspect every descendant for each ancestor, or carry the intersection of ancestor requirements as an open interval. Strict boundaries reject duplicates.
Reveal Naive Subtree Check: intuition, complexity, and code
4 below the right child 7 of root 5.When a rule involves every ancestor rather than only the parent, carry the accumulated constraint through the traversal instead of repeatedly scanning subtrees.