topic
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:
- A node's left subtree contains only numbers less than the current node.
- The right subtree of a node contains only numbers greater than the current node.
- All left and right subtrees must themselves be binary search trees.
Example 1:
Input: root = [2,1,3] Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The value of the root node is 5, but the value of the right child node is 4.
hint:
- The number of nodes in the tree
[1, 104]
is within -231 <= Node.val <= 231 - 1
answer
source code
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST(TreeNode node, long low, long high) {
if (node == null) {
return true;
}
if (node.val <= low || node.val >= high) {
return false;
}
return isValidBST(node.left, low, node.val) && isValidBST(node.right, node.val, high);
}
}
Summarize
My initial idea was to compare the values of the left and right child nodes with the value of the current node during the traversal process, and return false if there is any problem, and return true if there is no problem after all traversal, but I did not notice that all the left subtrees are needed The nodes are all smaller than the current node, and all the nodes of the right subtree are larger than the current node, so after learning the idea of solving the problem, record the legal range of the current node every time it is traversed.
When recursively entering the left child node of the current node, because the nodes of the left subtree are smaller than the current node, the maximum value of the legal range of the node should be set to the current node, and the same is true for the right child node.