对判断二叉搜索树(BST)代码中某条件判断逻辑的疑问
Great question! Let's unpack this line of code and the overall logic behind it clearly.
Core Idea: Inorder Traversal for BST Validation
First, remember that a valid Binary Search Tree (BST) has a key property: its inorder traversal produces a strictly increasing sequence of values. This code leverages exactly that rule—it's performing an inorder traversal (left subtree → current node → right subtree) and checking if each node follows the strictly increasing rule.
What prev_node_list Does
The prev_node_list is a practical trick to track the last node we visited during traversal. Since Python passes variables by assignment, using a list (a mutable object) lets all recursive calls share and update the same "previous node" reference—something we couldn't do with a regular variable (each recursive stack would have its own independent copy).
Breaking Down the Critical Line: if (prev_node and cur_node.data <= prev_node.data): return False
Let's clarify why this check works, since it seems you might have mixed up the traversal order:
- When we traverse the left subtree first, we start from the smallest value in the tree (the leftmost node) and move upwards. Each subsequent node we visit in the inorder sequence should be larger than the last one.
prev_nodeholds the last node we processed. For a valid BST, the current node's value must be strictly greater thanprev_node's value. If it's less than or equal, that breaks the strictly increasing rule—so we immediately returnFalsebecause this can't be a valid BST.
Example to Illustrate
Suppose we have an invalid tree where a node's left child has a larger value than itself:
3 / 4
The inorder traversal would be 4 → 3. When processing the 3 node:
prev_nodeis4(from the left subtree traversal)3 <= 4is true, so the code returnsFalse—correctly identifying this as an invalid BST.
If we had a valid BST like:
3 / \ 2 4
Inorder traversal is 2 → 3 →4. Each step passes the check:
2has no previous node, so no check fails3 > 2passes4 >3passes
The code returnsTrue.
内容的提问来源于stack exchange,提问作者anon anon

