[Recursive Algorithm Practice] Verifying Binary Search Tree

Table of contents

1. Recursive algorithm

2. Recursive implementation to verify binary search tree

3. Implementation logic of recursive solution

4. Example analysis of recursive implementation


1. Recursive algorithm

Recursion is an algorithm that solves problems by calling the function itself. It can make the code more concise and elegant, and can also solve many complex problems. In recursion, a function keeps calling itself to solve a smaller problem until the base case is reached.

Recursive algorithm (recursion algorithm) in computer science refers to a method of solving problems by repeatedly decomposing the problem into similar sub-problems. Recursive methods can be used to solve many computer science problems, so it is a very important concept in computer science.

2. Recursive implementation to verify binary search tree

topic:

https://leetcode.cn/problems/validate-binary-search-tree/

https://leetcode.com/problems/validate-binary-search-tree/

Given the root node of a binary tree  root , determine whether it is a valid binary search tree.

A valid  binary search tree is defined as follows:

  • The left subtree of a node only contains  numbers less than  the current node.
  • The right subtree of a node only contains  numbers greater than  the current node.
  • All left and right subtrees must themselves be binary search trees.

Code:

from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:

    def __init__(self) -> None:
        self.pre = float("-inf")

    # inorder traversal
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        if root is None :
            return True
        # 一直递进左子树中,直到遇到 None,这时候发生第一次的回归,
        # 然后执行下面几行代码,即进行值的判断,并且递进到右子树中,
        # 接着按照递进的反方向一层一层的回归
        if not self.isValidBST(root.left):
            return False
        if root.val <= self.pre:
            return False
        self.pre = root.val
        return self.isValidBST(root.right)

if __name__ == "__main__":
    solution = Solution()

    # a = TreeNode(4)
    root = TreeNode(0)
    # c = TreeNode(3)

    # root.left = a
    # root.right = c

    result = solution.isValidBST(root)
    print(result)

3. Implementation logic of recursive solution

In the `isValidBST` method, first determine whether the current node is None, and if so, return True, indicating that the current subtree is a valid BST. Then, recursively determine whether the left subtree is a BST, and return False if not. Then, determine whether the value of the current node is less than or equal to the value of the previous node `pre`, and return False if it is less than or equal to. Finally, assign the value of the current node to `pre`, and recursively determine whether the right subtree is BST, and return False if not.

If the above conditions are met, the binary tree is a valid BST and True is returned.

In the `isValidBST` method, if the left subtree or right subtree is not BST, False is returned instead of True. This is because when judging whether a binary tree is BST, as long as it is found that its left subtree or right subtree is not BST, you can be sure that the binary tree is not BST, and there is no need to continue traversing it.

If a node that does not conform to BST is found in the left subtree or right subtree, then its parent node and its ancestor nodes cannot be BST, because the definition of BST requires that all nodes of the left subtree are smaller than the root node, All nodes in the right subtree are greater than the root node. Therefore, if the left subtree or the right subtree is not BST, you can directly return False without continuing to traverse, which can improve the efficiency of the program.

4. Example analysis of recursive implementation

The `isValidBST` function is a function that verifies a binary search tree. An example is used below to gradually explain the recursive execution process and code implementation ideas.

Suppose we have the following binary tree:

```
5
/ \\
1 7
/ \\
6 8
```

We first call the `isValidBST` function, passing in the root node `5`. Since `root` is not empty, we continue executing the function. Since `root` has a left child node `1`, we call the `isValidBST` function recursively, passing in `1` as a parameter. Since `1` has no left or right child, we directly return `True`. At this point, we return to the function call of the root node `5`.

Since `root` has a left child node, we have just recursively called the `isValidBST` function, which will return `True`. We continue to execute the function and check whether the value of `root` is greater than the value of the previous node. Since this is the first node and the value of the previous node is negative infinity, this condition is met. We set the value of `pre` to `5` and continue executing the function.

Since `root` has a right child node `7`, we call the `isValidBST` function recursively, passing in `7` as a parameter. Since `7` has a left child node `6`, we continue to call the `isValidBST` function recursively, passing in `6` as a parameter. Since `6` has no left or right child node, we directly return `True`. At this point, we are back to the function call at node `7`.

Since the left child node `6` of `7` has been processed, we continue to execute the function and check whether the value of `root` is greater than the value of the previous node. Since `7` is greater than `5`, this condition is met. We set the value of `pre` to `7` and continue executing the function.

Since `7` has a right child node `8`, we call the `isValidBST` function recursively, passing in `8` as a parameter. Since `8` has no left or right child node, we directly return `True`. At this point, we are back to the function call at node `7`.

Since the right subtree of `root` has been processed, we return to the function call of the root node `5`. Since the left subtree and right subtree of the root node `5` have been processed and meet the definition of a binary search tree, the entire function returns `True`, indicating that this binary tree is a legal binary search tree.

The idea of ​​​​implementing this code is that for each node, check whether it is greater than the value of the previous node. Since inorder traversal of a binary search tree is in order, the value of the previous node should be smaller than the value of the current node. If the value of the previous node is greater than the value of the current node, it means that this binary tree is not a legal binary search tree.

Guess you like

Origin blog.csdn.net/u014147522/article/details/132184535