Problem
Problem page: https://leetcode.com/problems/validate-binary-search-tree/
Topics: Tree, Depth-first Search
Difficulty: Medium
Similar problems: (M) Binary Tree Inorder Traversal
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
confused what
"{1,#,2,3}"means?OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}".
Analysis
Check whether a binary tree is a valid binary search tree (BST). Watch out for the definition of a BST: it's not enough for the left child's value to be less than the current node's value. Every value in the left subtree has to be smaller (a BST is different from a heap, where the ordering only has to hold between each node and its immediate children). On the right, the subtree's values all have to be larger than the current node's value. I use recursion to check whether each subtree is a BST. When I backtrack, I return the result of the check along with the largest and smallest node values in the current subtree to the previous level of recursion. In Python, return can give you a tuple, so you can return several variables at once, which is really handy.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-validate-binary-search-tree/
