You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对判断二叉搜索树(BST)代码中某条件判断逻辑的疑问

Understanding the BST Validation Logic in Your Code

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_node holds the last node we processed. For a valid BST, the current node's value must be strictly greater than prev_node's value. If it's less than or equal, that breaks the strictly increasing rule—so we immediately return False because 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_node is 4 (from the left subtree traversal)
  • 3 <= 4 is true, so the code returns False—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:

  • 2 has no previous node, so no check fails
  • 3 > 2 passes
  • 4 >3 passes
    The code returns True.

内容的提问来源于stack exchange,提问作者anon anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:01:17