[LeetCode in Python] 98 (M) validate binary search tree

topic

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

Given a binary tree, determine whether it is a valid binary search tree.
Suppose a binary search tree has the following characteristics:

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

Example 1:

Enter:

    2
   / \
  1   3

Output: true

Example 2:

Enter:

    5
   / \
  1   4
     / \
    3   6

Output: false

Explanation: The input is: [5,1,4, null, null, 3,6].
  The root node has a value of 5, but its right child node has a value of 4.

Problem-solving ideas

  • DFS
  • It is not enough to just view the current node and the nodes of the left and right subtrees
  • Also need to maintain a minimum and maximum extreme value to judge

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isValidBST(self, root: TreeNode) -> bool:

        def dfs(node, min_node, max_node):
            if not node: return True

            # - check node
            if min_node and (node.val <= min_node.val): return False
            if max_node and (node.val >= max_node.val): return False

            # - dfs left and right branch
            if node.left and (not dfs(node.left, min_node, node)): return False
            if node.right and (not dfs(node.right, node, max_node)): return False

            return True

        return dfs(root, None, None)

Guess you like

Origin www.cnblogs.com/journeyonmyway/p/12749395.html