{"id":"validate-binary-search-tree","title":"Validate Binary Search Tree","difficulty":"medium","patterns":["tree-dfs"],"primaryConcept":"tree-dfs-basics","concepts":["tree-dfs-basics"],"problemForm":"core","companies":[],"category":"trees-graphs","compareMode":"exact","description":"Given the root of a binary tree, return whether it is a valid binary search tree.\n\nRequirements:\n- Every node in the left subtree must be strictly less than the current node.\n- Every node in the right subtree must be strictly greater than the current node.\n- The rule applies to the entire subtree, not just each direct child.","examples":[{"input":"root = {\"val\":2,\"left\":{\"val\":1},\"right\":{\"val\":3}}","output":"true","explanation":"Every left value is less than 2 and every right value is greater than 2."},{"input":"root = {\"val\":5,\"left\":{\"val\":1},\"right\":{\"val\":4,\"left\":{\"val\":3},\"right\":{\"val\":6}}}","output":"false","explanation":"The value 4 is in the right subtree of 5 but is less than 5."},{"input":"root = {\"val\":1,\"right\":{\"val\":1}}","output":"false","explanation":"Duplicate values are not allowed in a valid BST."}],"constraints":[{"id":"the-number-of-nodes-in-the-tree-is-in-the-range-0-10-4","text":"The number of nodes in the tree is in the range [0, 10^4]","check":{"kind":"sizeRange","target":"root","measure":"treeNodes","min":0,"max":10000}},{"id":"2-31-node-val-2-31-1","text":"-2^31 <= Node.val <= 2^31 - 1","check":{"kind":"valueRange","target":"root","selector":"treeValues","min":-2147483648,"max":2147483647}},{"id":"bst-ordering-is-strict-duplicates-make-the-tree-invalid","text":"BST ordering is strict: duplicates make the tree invalid"}],"starterCode":"# TraceCode provides TreeNode at runtime.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\n\nclass Solution:\n    def isValidBST(self, root) -> bool:\n        # Your code here\n        pass","functionName":"isValidBST","testCases":[{"id":"1","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":2,"left":{"__type__":"TreeNode","__id__":"tree-1","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-2","val":3,"left":null,"right":null}}},"expected":true,"description":"Simple valid BST."},{"id":"2","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":5,"left":{"__type__":"TreeNode","__id__":"tree-1","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-2","val":4,"left":{"__type__":"TreeNode","__id__":"tree-3","val":3,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"tree-4","val":6,"left":null,"right":null}}}},"expected":false,"description":"Right subtree violates the root's lower bound."},{"id":"3","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-1","val":1,"left":null,"right":null}}},"expected":false,"description":"Imported seed case with duplicate value."},{"id":"4","input":{"root":null},"expected":true,"description":"Empty tree is valid."},{"id":"5","input":{"root":{"__type__":"TreeNode","__id__":"tree-0","val":10,"left":{"__type__":"TreeNode","__id__":"tree-1","val":5,"left":null,"right":{"__type__":"TreeNode","__id__":"tree-2","val":12,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"tree-3","val":15,"left":null,"right":null}}},"expected":false,"description":"A left-subtree descendant violates the root's upper bound."},{"id":"h1","input":{"root":{"__type__":"TreeNode","__id__":"v1-0","val":1,"left":null,"right":{"__type__":"TreeNode","__id__":"v1-1","val":2,"left":null,"right":null}}},"expected":true,"description":"A root with a valid right child respects the lower bound."},{"id":"h2","input":{"root":{"__type__":"TreeNode","__id__":"v2-0","val":2,"left":null,"right":null}},"expected":true,"description":"A single node is always a valid BST."},{"id":"h3","input":{"root":{"__type__":"TreeNode","__id__":"v3-0","val":8,"left":{"__type__":"TreeNode","__id__":"v3-1","val":4,"left":{"__type__":"TreeNode","__id__":"v3-3","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"v3-4","val":6,"left":null,"right":null}},"right":{"__type__":"TreeNode","__id__":"v3-2","val":12,"left":{"__type__":"TreeNode","__id__":"v3-5","val":10,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"v3-6","val":14,"left":null,"right":null}}}},"expected":true,"description":"A deeper balanced BST stays valid across multiple levels."},{"id":"h4","input":{"root":{"__type__":"TreeNode","__id__":"v4-0","val":2,"left":{"__type__":"TreeNode","__id__":"v4-1","val":2,"left":null,"right":null},"right":null}},"expected":false,"description":"Duplicate values on the left break strict ordering."},{"id":"h5","input":{"root":{"__type__":"TreeNode","__id__":"v5-0","val":5,"left":{"__type__":"TreeNode","__id__":"v5-1","val":1,"left":null,"right":null},"right":{"__type__":"TreeNode","__id__":"v5-2","val":7,"left":{"__type__":"TreeNode","__id__":"v5-3","val":4,"left":null,"right":null},"right":null}}},"expected":false,"description":"A descendant in the right subtree can still violate the root bound."},{"id":"valid-signed-bst","input":{"root":{"__type__":"TreeNode","val":0,"left":{"__type__":"TreeNode","val":-3,"left":{"__type__":"TreeNode","val":-4,"left":null,"right":null},"right":{"__type__":"TreeNode","val":-1,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":5,"left":{"__type__":"TreeNode","val":2,"left":null,"right":null},"right":{"__type__":"TreeNode","val":9,"left":null,"right":null}}}},"expected":true,"description":"A valid BST may contain zero and negative values as long as strict ordering holds."},{"id":"topup-invalid-deep-boundary","input":{"root":{"__type__":"TreeNode","val":10,"left":{"__type__":"TreeNode","val":5,"left":null,"right":{"__type__":"TreeNode","val":12,"left":null,"right":null}},"right":{"__type__":"TreeNode","val":15,"left":null,"right":null}}},"expected":false,"description":"A deep left-subtree value greater than the root violates BST bounds."}],"hints":[{"level":1,"content":"A node's value must fit inside a range inherited from every ancestor.","revealPattern":false},{"level":2,"content":"Pass lower and upper bounds into a DFS helper.","revealPattern":true},{"level":3,"content":"For the left child, the current value becomes the upper bound; for the right child, it becomes the lower bound.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach checks each node against its ancestor bounds?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"inorder-increasing","name":"In-order traversal must be strictly increasing","summary":"Visit the tree left, node, right, recording each value, and confirm every value is strictly larger than the one before it.","decisionReason":"A strictly increasing inorder traversal returns the same BST verdict in O(n) time. The guided implementation carries ancestor bounds so each node is checked against the exact interval it inherits.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["and O(n), but it routes the check through a sorted-order property and must track the previously visited value across the whole traversal."],"isViable":true,"isOptimal":false},{"id":"bounds-dfs","name":"DFS with lower and upper bounds","summary":"Each recursive call verifies the node value against ancestor-derived bounds, then tightens one bound for each child.","decisionReason":"Carry an allowed low-to-high range down to each node, tightening it on the way, so every node is checked against its whole ancestry in one pass.","complexity":{"time":"O(n)","space":"O(h)"},"tradeoffs":["Runs in O(n) time and uses O(h) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"start-unbounded-helper","title":"Start with unbounded root bounds","description":"Call the bounded helper on the root with no ancestor-imposed lower or upper value yet.","commonMistakes":["Starting with root value as one of its own bounds","Using fixed problem-value sentinels that can collide with valid node values"],"hint":"The root has no ancestor, so its allowed range starts open on both sides.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"checks_bst_node_value_within_bounds","scope":"initial-call","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Seed recursive BST validation with an unrestricted root range.","doneWhen":"This step is done when the public function starts helper validation at the root with lower and upper bounds that do not exclude any valid root value.","shouldFailWhen":"This step should fail if the initial call uses the root value as a bound, omits one side of the range, or uses finite sentinels that can conflict with allowed values.","roles":["root node","initial lower bound","initial upper bound","helper call"],"mustProve":["The helper is called on the root.","The initial lower bound is open or below every valid node value.","The initial upper bound is open or above every valid node value."],"mustNotAccept":["Calling the helper first on a child.","Starting with the root value as an active bound."],"equivalentVariants":["Use negative and positive infinity.","Use nullable/open bounds.","Use any language-appropriate unbounded sentinel outside the input domain."]}},{"id":"null-base-case","title":"Accept missing nodes as valid leaves","description":"Return true for a missing node before performing value comparisons.","commonMistakes":["Treating null as a bounds violation","Reading a value from a missing node"],"hint":"A missing subtree has no value that can violate the active bounds.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_bst_bounds_conjunction","scope":"base-case","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Handle the recursive base case for an absent subtree.","doneWhen":"This step is done when the helper returns true for a missing node before comparing values or recursing.","shouldFailWhen":"This step should fail if null is rejected, dereferenced, or allowed to fall through into bound comparisons.","roles":["missing node","base case","boolean return"],"mustProve":["A missing node returns true.","The base case runs before node value comparisons."],"mustNotAccept":["Rejecting an empty subtree.","Reading node.val before checking that node exists."],"equivalentVariants":["Use `if node is null: return true`.","Use any equivalent missing-node guard before value access."]}},{"id":"check-bounds","title":"Check the current value range","description":"Reject a node whose value is outside its allowed low/high bounds.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"checks_bst_node_value_within_bounds","scope":"check-bounds","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using non-strict comparisons and allowing duplicates","Comparing only to the parent value"],"hint":"The current node must satisfy `low < node.val < high`.","semanticSpec":{"intent":"Verify each visited node against inherited BST bounds.","doneWhen":"This step is done when the recursive helper rejects values outside the current low/high range.","shouldFailWhen":"This step should fail if the code does not compare node value against both bounds.","roles":["node value","lower bound","upper bound"],"mustProve":["The current node value is compared with both lower and upper bounds."],"mustNotAccept":["Checking only direct child values.","Checking only one side of the range."],"equivalentVariants":["Use `if not (low < node.val < high): return False`.","Use equivalent strict lower and upper comparisons."],"proofSnippets":[{"id":"py-validate-bst-check-bounds","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return True\n        return validate(root, float('-inf'), float('inf'))"}]}},{"id":"left-bound","title":"Tighten the upper bound on the left","description":"Recurse into the left subtree with the current value as the new upper bound.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"propagates_bst_left_upper_bound","scope":"left-bound","readMode":"tree-value-query-v1"}]},"commonMistakes":["Passing the old high bound to the left child","Using the current value as the lower bound for the left child"],"hint":"Left descendants must be less than the current node.","semanticSpec":{"intent":"Propagate the current node value as the upper bound for the left subtree.","doneWhen":"This step is done when the left recursive call receives `(low, node.val)` as its bounds.","shouldFailWhen":"This step should fail if the left child does not receive the tightened upper bound.","roles":["left subtree","upper bound","current node value"],"mustProve":["The left recursive call keeps the lower bound and uses node value as upper bound."],"mustNotAccept":["Calling left with unchanged bounds.","Using node value as the lower bound for left."],"equivalentVariants":["Use `validate(node.left, low, node.val)`."],"proofSnippets":[{"id":"py-validate-bst-left-bound","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return validate(node.left, low, node.val)\n        return validate(root, float('-inf'), float('inf'))"}]}},{"id":"right-bound","title":"Tighten the lower bound on the right","description":"Recurse into the right subtree with the current value as the new lower bound.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"propagates_bst_right_lower_bound","scope":"right-bound","readMode":"tree-value-query-v1"}]},"commonMistakes":["Passing the old low bound to the right child","Using the current value as the upper bound for the right child"],"hint":"Right descendants must be greater than the current node.","semanticSpec":{"intent":"Propagate the current node value as the lower bound for the right subtree.","doneWhen":"This step is done when the right recursive call receives `(node.val, high)` as its bounds.","shouldFailWhen":"This step should fail if the right child does not receive the tightened lower bound.","roles":["right subtree","lower bound","current node value"],"mustProve":["The right recursive call uses node value as lower bound and keeps the upper bound."],"mustNotAccept":["Calling right with unchanged bounds.","Using node value as the upper bound for right."],"equivalentVariants":["Use `validate(node.right, node.val, high)`."],"proofSnippets":[{"id":"py-validate-bst-right-bound","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return validate(node.left, low, node.val) or validate(node.right, node.val, high)\n        return validate(root, float('-inf'), float('inf'))"}]}},{"id":"return-validation","title":"Require both subtrees to be valid","description":"Return true only when both bounded recursive checks pass.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_bst_bounds_conjunction","scope":"return-value","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using or between the subtree checks","Returning only one subtree's result"],"hint":"Both recursive calls must be true.","semanticSpec":{"intent":"Combine left and right bounded validation with logical and.","doneWhen":"This step is done when the helper returns the conjunction of the left and right subtree validations.","shouldFailWhen":"This step should fail if either subtree can be ignored.","roles":["left recursive result","right recursive result","boolean conjunction"],"mustProve":["Both child validations are returned together.","The combination requires both sides to pass."],"mustNotAccept":["Using `or` between child validations.","Returning only left or only right."],"equivalentVariants":["Use `return validate(node.left, low, node.val) and validate(node.right, node.val, high)`."],"proofSnippets":[{"id":"py-validate-bst-return","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return validate(node.left, low, node.val) and validate(node.right, node.val, high)\n        return validate(root, float('-inf'), float('inf'))"}]}}],"version":2,"slides":[{"id":"read-the-signal","chapter":"The tree","kind":"info","eyebrow":"Read the problem","title":"Is this a valid search tree?","workspacePanel":"problem","body":["A binary search tree keeps an order: every value in a node left subtree is smaller than the node, and every value in its right subtree is larger. The job is to say whether a tree obeys that rule everywhere.","Take the tree 5 with left child 3 and right child 8, and below 3 the children 1 and 4. Every value on the left of 5 is below it, every value on the right is above it, and the same holds at 3, so this tree is valid.","Change one number and it can break. The question is how to check the rule at every node without missing anything."]},{"id":"naive-local-check","chapter":"The obvious way","kind":"code-trace","eyebrow":"The obvious way","title":"Compare each node with its two children","summary":"It passes every valid tree, and it is quick. Watch what it does on a tree where a deep node breaks a far ancestor.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def valid(node: TreeNode | None) -> bool:\n    if node is None:\n        return True\n    if node.left and node.left.val >= node.val:\n        return False\n    if node.right and node.right.val <= node.val:\n        return False\n    return valid(node.left) and valid(node.right)","steps":[{"id":"root-ok","title":"The root passes its local check","codeLine":4,"summary":"Tree is 5 with children 4 and 6. 4 is below 5 and 6 is above 5, so the root looks fine one level down.","state":{"tree":[5,4,6,null,null,3,7],"node":0}},{"id":"six-ok-locally","title":"Node 6 passes against its children","codeLine":6,"summary":"Node 6 has children 3 and 7. 3 is below 6 and 7 is above 6, so 6 passes too, one level at a time.","state":{"tree":[5,4,6,null,null,3,7],"node":2,"visited":[0]}},{"id":"returns-valid","title":"Every local check passed","codeLine":8,"summary":"No parent-child pair was out of order, so the code returns valid. But 3 sits in the right subtree of 5 and is below 5, which the check never compared.","state":{"tree":[5,4,6,null,null,3,7],"node":5,"visited":[0,2]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (node === null) {\n    return true;\n}\nif (node.left != null && node.left.val >= node.val) {\n    return false;\n}\nif (node.right != null && node.right.val <= node.val) {\n    return false;\n}\nreturn (valid(node.left) && valid(node.right));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (node === null) {\n    return true;\n}\nif (node.left != null && node.left.val >= node.val) {\n    return false;\n}\nif (node.right != null && node.right.val <= node.val) {\n    return false;\n}\nreturn (valid(node.left) && valid(node.right));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (node == null) {\n    return true;\n}\nif (node.left != null && node.left.val >= node.val) {\n    return false;\n}\nif (node.right != null && node.right.val <= node.val) {\n    return false;\n}\nreturn (valid(node.left) && valid(node.right));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (node == null) {\n    return true;\n}\nif (node.left != null && node.left.val >= node.val) {\n    return false;\n}\nif (node.right != null && node.right.val <= node.val) {\n    return false;\n}\nreturn Valid(node.left) && Valid(node.right);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (node == nullptr) {\n    return true;\n}\nif ((node->left && node->left->val >= node->val)) {\n    return false;\n}\nif ((node->right && node->right->val <= node->val)) {\n    return false;\n}\nreturn (valid(node->left) && valid(node->right));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7,"7":8,"8":10},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":9}}}}}},{"id":"local-check-cost","chapter":"The obvious way","kind":"case-probe","eyebrow":"Name the gap","title":"Why did the local check call a broken tree valid?","summary":"Node 3 sits in the right subtree of 5, and the code returned valid anyway.","workspacePanel":"trace","options":[{"id":"skips-ancestors","label":"It only ever compared 3 with its parent 6, never with the ancestor 5 above","rationale":"3 is below 6, which the local rule allows. Nothing ever checked 3 against 5, so the rule that every right-subtree value beats 5 went untested.","isCorrect":true},{"id":"wrong-order","label":"It compared the children in the wrong order","rationale":"Order of the two child checks does not matter. Each pair was compared correctly; the gap is that ancestors two levels up were never part of any comparison.","isCorrect":false},{"id":"missed-leaf","label":"It skipped node 3 because it is a leaf","rationale":"Node 3 was visited and checked against its own children. The missing comparison is the one against 5.","isCorrect":false}],"answer":"The local check only ever looks one level down. To catch 3 breaking 5, each node has to satisfy every ancestor bound."},{"id":"whole-ancestry","chapter":"The idea","kind":"info","eyebrow":"See the shape","title":"Look at node 4 and the path above it","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"tree-intro","state":{"tree":[5,3,8,1,4,7,9],"node":4}}]},"body":["Node 4 is the right child of 3, and 3 is the left child of 5. So 4 has two ancestors above it: 3 and 5.","Being the right child of 3 means 4 has to be larger than 3. Sitting in the left subtree of 5 means it also has to be smaller than 5.","Both ancestors apply at once. A node needs one allowed range that combines them."]},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"tree":[5,3,8,1,4,7,9],"node":0}}]}},{"id":"allowed-range","chapter":"The idea","kind":"case-probe","eyebrow":"Name the state","title":"What does each node really have to satisfy?","summary":"Node 4 has ancestors 3 and 5 sitting above it.","workspacePanel":"visualizer","options":[{"id":"range","label":"Its value falls inside a low-to-high range inherited from its ancestors","rationale":"Every ancestor pins the node above or below itself. Together they form one allowed band, and the node is valid exactly when its value lands inside it.","isCorrect":true},{"id":"children-only","label":"It is larger than its left child and smaller than its right child","rationale":"That only checks one level. A node can satisfy its own children yet still violate a grandparent far above, so the local check misses real errors.","isCorrect":false},{"id":"root-only","label":"It is on the correct side of the root","rationale":"The root is just one ancestor. A node must respect every ancestor between it and the root.","isCorrect":false}],"answer":"It must fall inside a low-to-high range built from all its ancestors. A node is valid when its value sits strictly inside that band.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"allowed-range-state","state":{"tree":[5,3,8,1,4,7,9],"node":4,"low":3,"high":5}}]}},{"id":"narrow-range","chapter":"The idea","kind":"case-probe","eyebrow":"Pass it down","title":"Stepping to a child, how does the allowed range change?","summary":"You are moving from a parent down to one child, carrying the current allowed range.","workspacePanel":"visualizer","options":[{"id":"left-ceiling-right-floor","label":"Go left and the node becomes the new ceiling; go right and it becomes the new floor","rationale":"Everything left of a node must be below it, so the upper limit drops to the node value. Everything right must be above it, so the lower limit rises to the node value.","isCorrect":true},{"id":"reset","label":"The range resets to all values at each child","rationale":"Constraints accumulate, they never reset. Forgetting the ancestors is exactly what lets a deep node slip through.","isCorrect":false},{"id":"both-tighten","label":"Both the floor and ceiling move to the node value","rationale":"Only one side tightens per step. Going left lowers the ceiling but keeps the inherited floor; going right does the reverse.","isCorrect":false}],"answer":"Going left, the node becomes the new upper bound; going right, it becomes the new lower bound. The other side stays as inherited, so the band only narrows.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"narrow-range-state","state":{"tree":[5,3,8,1,4,7,9],"node":1,"low":null,"high":3}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Carry the range down the tree","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"tree":[5,3,8,1,4,7,9],"node":0}}]},"body":["The root may hold any value, so it starts with no floor and no ceiling. Each node checks that it lands inside its current range.","Going left passes down the same floor but a ceiling of the current node. Going right passes down the same ceiling but a floor of the current node.","If every node fits its range, the tree is valid; the first node that falls outside makes the whole tree invalid."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the range","title":"Trace the narrowing range","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"left-of-root","state":{"tree":[5,3,8,1,4,7,9],"node":1}},{"id":"right-of-three","state":{"tree":[5,3,8,1,4,7,9],"node":4}},{"id":"right-subtree","state":{"tree":[5,3,8,1,4,7,9],"node":5}}]},"beats":[{"id":"left-of-root","title":"Going left from root 5 to node 3, what range must 3 fit?","summary":"The root had no limits. Node 3 is its left child.","prompt":"You step left from 5 into node 3.","options":[{"id":"below-five","label":"Anything below 5","rationale":"Going left makes 5 the ceiling, and there was no floor, so 3 must be below 5. It is, so 3 is fine.","isCorrect":true},{"id":"above-five","label":"Anything above 5","rationale":"That would be the rule for going right. Left of a node means smaller, so the ceiling drops to 5.","isCorrect":false},{"id":"anything","label":"Any value at all","rationale":"The root passed down a ceiling of 5 by going left. The range is no longer unlimited.","isCorrect":false}],"answer":"Below 5. Going left set the ceiling to 5, with no floor yet, and 3 fits."},{"id":"right-of-three","title":"From node 3, going right to node 4, what is the range now?","summary":"Node 3 sits inside the left subtree of 5, with a ceiling of 5.","prompt":"You step right from 3 into node 4.","options":[{"id":"three-to-five","label":"Between 3 and 5","rationale":"Going right from 3 raises the floor to 3, and the ceiling of 5 is still inherited from being left of the root. 4 lands inside, so it is valid.","isCorrect":true},{"id":"above-three","label":"Anything above 3","rationale":"The ceiling of 5 does not vanish. Node 4 must stay both above 3 and below 5, or it would break the root order.","isCorrect":false},{"id":"three-to-infinity","label":"Between 3 and anything","rationale":"The inherited ceiling of 5 still applies. A value like 6 here would be invalid despite beating 3.","isCorrect":false}],"answer":"Between 3 and 5. The floor rose to 3, the ceiling of 5 carried down, and 4 fits the band."},{"id":"right-subtree","title":"Over in the right subtree, node 7 sits below 8 and right of 5. Valid?","summary":"Node 7 is the left child of 8, which is the right child of 5.","prompt":"Node 7 must satisfy its inherited range.","options":[{"id":"yes","label":"Yes: 7 is between 5 and 8","rationale":"Right of 5 set the floor to 5; left of 8 set the ceiling to 8. 7 sits inside (5, 8), so it holds.","isCorrect":true},{"id":"no-below-eight","label":"No, it only needs to be below 8","rationale":"It also inherited a floor of 5 from being in the right subtree of the root. Both bounds apply, and 7 meets both.","isCorrect":false},{"id":"no-leaf","label":"No, leaves are not checked","rationale":"Every node is checked against its range, leaves included. 7 passes, so the whole tree comes out valid.","isCorrect":false}],"answer":"Yes. 7 lands inside (5, 8), and since every node fits its range, the tree is a valid BST."}]},{"id":"wrong-bound-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"What if the left child keeps the inherited upper bound?","summary":"This version carries bounds correctly on the right, but on the left it passes the same `high` it received instead of tightening it to the current value. It still rejects many bad trees. Watch it on a left descendant that climbs above its grandparent.","workspacePanel":"trace","pitfall":"On the left recursion this code forgets to drop the upper bound to the current node value.","whyItMatters":"Going left, the current node must become the new upper bound, or a left descendant can exceed an ancestor unchecked. The left call must be validate(node.left, low, node.val), not validate(node.left, low, high).","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def validate(node: TreeNode | None, low: float, high: float) -> bool:\n    if node is None:\n        return True\n    if not (low < node.val < high):\n        return False\n    return validate(node.left, low, high) and validate(node.right, node.val, high)","steps":[{"id":"root-ok","title":"Root 10 passes its open range","codeLine":4,"summary":"Tree is 10 with left child 5, and 5 has a right child 12. The root starts with low=-inf, high=inf, and 10 fits.","state":{"tree":[10,5,15,null,12],"node":0,"low":null,"high":null}},{"id":"left-keeps-high","title":"Going left, high stays inf instead of dropping to 10","codeLine":6,"summary":"The correct call would pass high=10 to the left child. This version passes the inherited high=inf, so 5 is checked against (-inf, inf) instead of (-inf, 10).","state":{"tree":[10,5,15,null,12],"node":1,"low":null,"high":null,"visited":[0]}},{"id":"twelve-slips-through","title":"12 passes when it should fail","codeLine":4,"summary":"From 5 we go right to 12 with bounds (5, inf). 12 sits inside, so it passes, and the tree is called valid. But 12 is in the left subtree of 10 and must stay below 10. The lost upper bound let it slip through.","state":{"tree":[10,5,15,null,12],"node":4,"low":5,"high":null,"visited":[0,1]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (node === null) {\n    return true;\n}\nif (!(((low < node.val) && (node.val < high)))) {\n    return false;\n}\nreturn (validate(node.left, low, high) && validate(node.right, node.val, high));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (node === null) {\n    return true;\n}\nif (!(((low < node.val) && (node.val < high)))) {\n    return false;\n}\nreturn (validate(node.left, low, high) && validate(node.right, node.val, high));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if (node == null) {\n    return true;\n}\nif (!(low < node.val && node.val < high)) {\n    return false;\n}\nreturn (validate(node.left, low, high) && validate(node.right, node.val, high));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (node == null) {\n    return true;\n}\nif (!(low < node.val && node.val < high)) {\n    return false;\n}\nreturn Validate(node.left, low, high) && Validate(node.right, node.val, high);","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if (node == nullptr) {\n    return true;\n}\nif (!(low < node->val && node->val < high)) {\n    return false;\n}\nreturn (validate(node->left, low, high) && validate(node->right, node->val, high));","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":7},"statementBundles":{"3":{"startLine":2,"endLine":3},"5":{"startLine":5,"endLine":6}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Carrying a narrowing range down the tree held for a full example. A check like this is easiest to break on the smallest trees and on the boundary the order rule depends on.","Two inputs are worth checking before coding: a single node, and a child whose value equals its parent. Use the range rule to decide each one."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"tree":[5,3,8,1,4,7,9],"node":0}}]}},{"id":"single-node-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"Is a tree of a single node a valid search tree?","summary":"A lone node with no children, the smallest tree to classify.","workspacePanel":"visualizer","options":[{"id":"valid","label":"Yes, trivially","rationale":"With no children, there is no pair to put out of order. The node fits its unlimited range, so the tree is valid.","isCorrect":true},{"id":"invalid","label":"No, it has no subtrees to compare","rationale":"The rule only forbids out-of-order values. Having no subtrees means nothing can be out of order, which is valid.","isCorrect":false},{"id":"depends","label":"Only if its value is positive","rationale":"The values themselves are unrestricted; any single value, negative or not, forms a valid one-node tree.","isCorrect":false}],"answer":"Yes. A single node has no ordering to break and fits its open range, so it is a valid BST.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-node-state","state":{"tree":[5],"node":0}}]}},{"id":"duplicate-value-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"When a node equals its parent, is it valid?","summary":"A two-node tree, where a left child holds the same value as its parent.","workspacePanel":"visualizer","options":[{"id":"invalid","label":"Invalid, equal is not strictly smaller","rationale":"A left subtree must be strictly less than the node. An equal value violates the strict range, so the tree is invalid.","isCorrect":true},{"id":"valid","label":"Valid, equal is close enough","rationale":"The rule is strict: left values must be below the node, not equal to it. A tie breaks the order.","isCorrect":false},{"id":"depends","label":"Valid on the right, invalid on the left","rationale":"Both sides are strict. An equal value fails whether it sits left (must be smaller) or right (must be larger).","isCorrect":false}],"answer":"Invalid. A left child must be strictly smaller, so a value equal to its parent falls outside the allowed range.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"duplicate-value-edge-state","state":{"tree":[5,5],"node":1,"low":null,"high":5}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Carry a range down the tree","summary":"Each node answers to a whole range from its ancestors.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"tree":[5,3,8,1,4,7,9],"node":0}}]},"body":["Recurse from the root with no floor and no ceiling. Check each node lands inside its range, then go left with the node as the new ceiling and right with it as the new floor."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the bounded check","eyebrow":"Code the rule","summary":"Follow the bounded DFS moves in order.","workspacePanel":"code","checkpoints":[{"id":"start-unbounded-helper","title":"Start with unbounded root bounds","description":"Call the bounded helper on the root with no ancestor-imposed lower or upper value yet.","commonMistakes":["Starting with root value as one of its own bounds","Using fixed problem-value sentinels that can collide with valid node values"],"hint":"The root has no ancestor, so its allowed range starts open on both sides.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"checks_bst_node_value_within_bounds","scope":"initial-call","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Seed recursive BST validation with an unrestricted root range.","doneWhen":"This step is done when the public function starts helper validation at the root with lower and upper bounds that do not exclude any valid root value.","shouldFailWhen":"This step should fail if the initial call uses the root value as a bound, omits one side of the range, or uses finite sentinels that can conflict with allowed values.","roles":["root node","initial lower bound","initial upper bound","helper call"],"mustProve":["The helper is called on the root.","The initial lower bound is open or below every valid node value.","The initial upper bound is open or above every valid node value."],"mustNotAccept":["Calling the helper first on a child.","Starting with the root value as an active bound."],"equivalentVariants":["Use negative and positive infinity.","Use nullable/open bounds.","Use any language-appropriate unbounded sentinel outside the input domain."]}},{"id":"null-base-case","title":"Accept missing nodes as valid leaves","description":"Return true for a missing node before performing value comparisons.","commonMistakes":["Treating null as a bounds violation","Reading a value from a missing node"],"hint":"A missing subtree has no value that can violate the active bounds.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_bst_bounds_conjunction","scope":"base-case","readMode":"tree-value-query-v1"}]},"semanticSpec":{"intent":"Handle the recursive base case for an absent subtree.","doneWhen":"This step is done when the helper returns true for a missing node before comparing values or recursing.","shouldFailWhen":"This step should fail if null is rejected, dereferenced, or allowed to fall through into bound comparisons.","roles":["missing node","base case","boolean return"],"mustProve":["A missing node returns true.","The base case runs before node value comparisons."],"mustNotAccept":["Rejecting an empty subtree.","Reading node.val before checking that node exists."],"equivalentVariants":["Use `if node is null: return true`.","Use any equivalent missing-node guard before value access."]}},{"id":"check-bounds","title":"Check the current value range","description":"Reject a node whose value is outside its allowed low/high bounds.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"checks_bst_node_value_within_bounds","scope":"check-bounds","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using non-strict comparisons and allowing duplicates","Comparing only to the parent value"],"hint":"The current node must satisfy `low < node.val < high`.","semanticSpec":{"intent":"Verify each visited node against inherited BST bounds.","doneWhen":"This step is done when the recursive helper rejects values outside the current low/high range.","shouldFailWhen":"This step should fail if the code does not compare node value against both bounds.","roles":["node value","lower bound","upper bound"],"mustProve":["The current node value is compared with both lower and upper bounds."],"mustNotAccept":["Checking only direct child values.","Checking only one side of the range."],"equivalentVariants":["Use `if not (low < node.val < high): return False`.","Use equivalent strict lower and upper comparisons."],"proofSnippets":[{"id":"py-validate-bst-check-bounds","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return True\n        return validate(root, float('-inf'), float('inf'))"}]}},{"id":"left-bound","title":"Tighten the upper bound on the left","description":"Recurse into the left subtree with the current value as the new upper bound.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"propagates_bst_left_upper_bound","scope":"left-bound","readMode":"tree-value-query-v1"}]},"commonMistakes":["Passing the old high bound to the left child","Using the current value as the lower bound for the left child"],"hint":"Left descendants must be less than the current node.","semanticSpec":{"intent":"Propagate the current node value as the upper bound for the left subtree.","doneWhen":"This step is done when the left recursive call receives `(low, node.val)` as its bounds.","shouldFailWhen":"This step should fail if the left child does not receive the tightened upper bound.","roles":["left subtree","upper bound","current node value"],"mustProve":["The left recursive call keeps the lower bound and uses node value as upper bound."],"mustNotAccept":["Calling left with unchanged bounds.","Using node value as the lower bound for left."],"equivalentVariants":["Use `validate(node.left, low, node.val)`."],"proofSnippets":[{"id":"py-validate-bst-left-bound","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return validate(node.left, low, node.val)\n        return validate(root, float('-inf'), float('inf'))"}]}},{"id":"right-bound","title":"Tighten the lower bound on the right","description":"Recurse into the right subtree with the current value as the new lower bound.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"propagates_bst_right_lower_bound","scope":"right-bound","readMode":"tree-value-query-v1"}]},"commonMistakes":["Passing the old low bound to the right child","Using the current value as the upper bound for the right child"],"hint":"Right descendants must be greater than the current node.","semanticSpec":{"intent":"Propagate the current node value as the lower bound for the right subtree.","doneWhen":"This step is done when the right recursive call receives `(node.val, high)` as its bounds.","shouldFailWhen":"This step should fail if the right child does not receive the tightened lower bound.","roles":["right subtree","lower bound","current node value"],"mustProve":["The right recursive call uses node value as lower bound and keeps the upper bound."],"mustNotAccept":["Calling right with unchanged bounds.","Using node value as the upper bound for right."],"equivalentVariants":["Use `validate(node.right, node.val, high)`."],"proofSnippets":[{"id":"py-validate-bst-right-bound","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return validate(node.left, low, node.val) or validate(node.right, node.val, high)\n        return validate(root, float('-inf'), float('inf'))"}]}},{"id":"return-validation","title":"Require both subtrees to be valid","description":"Return true only when both bounded recursive checks pass.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree","fact":"returns_bst_bounds_conjunction","scope":"return-value","readMode":"tree-value-query-v1"}]},"commonMistakes":["Using or between the subtree checks","Returning only one subtree's result"],"hint":"Both recursive calls must be true.","semanticSpec":{"intent":"Combine left and right bounded validation with logical and.","doneWhen":"This step is done when the helper returns the conjunction of the left and right subtree validations.","shouldFailWhen":"This step should fail if either subtree can be ignored.","roles":["left recursive result","right recursive result","boolean conjunction"],"mustProve":["Both child validations are returned together.","The combination requires both sides to pass."],"mustNotAccept":["Using `or` between child validations.","Returning only left or only right."],"equivalentVariants":["Use `return validate(node.left, low, node.val) and validate(node.right, node.val, high)`."],"proofSnippets":[{"id":"py-validate-bst-return","language":"python","code":"class Solution:\n    def isValidBST(self, root):\n        def validate(node, low, high):\n            if not node:\n                return True\n            if not (low < node.val < high):\n                return False\n            return validate(node.left, low, node.val) and validate(node.right, node.val, high)\n        return validate(root, float('-inf'), float('inf'))"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Each node must fall inside a (low, high) range that tightens as you descend.","workspacePanel":"code","body":["Being larger than its parent is not enough; a node must respect every ancestor at once, which a running (low, high) bound captures.","Going left tightens the high bound to the node; going right tightens the low bound."],"takeaways":[{"title":"Compare to every ancestor","body":"The (low, high) window carries every constraint from above, so a value that slips past its parent but breaks a grandparent is still caught."},{"title":"The bounds are strict","body":"Equal values fail, since a BST demands strictly smaller on the left and strictly larger on the right."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"tree","primaryParam":"root","sizeMetric":"nodes","constraints":["binary-tree"]}}
