topic
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.
Example 1:
2 / \ 1 3Binary tree
[2,1,3]
, return true.
Example 2:
1 / \ 2 3Binary tree
[1,2,3]
, return false.
analyze
To determine whether the binary search tree is a binary search tree, through recursive post-order traversal, the maximum and minimum values of the left and right subtrees are recorded, and together with the value of the root node, it is judged whether it conforms to the requirements of the binary search tree.
class Solution { public: bool postOrder(TreeNode* root,int& subMin,int& subMax){ if(root==NULL)//When the root node is empty or reaches the leaf node, it conforms to the binary search tree return true; int leftMin=INT_MAX,leftMax=INT_MIN;//Record the maximum and minimum elements of the left subtree int rightMin=INT_MAX,rightMax=INT_MIN;//Record the maximum and minimum elements of the right subtree bool left=postOrder(root->left,leftMin,leftMax);//Determine whether the left subtree is a binary search tree bool right=postOrder(root->right,rightMin,rightMax);//Determine whether the right subtree is a binary search tree subMin=min(min(leftMin,rightMin),root->val);//Include the root node to calculate the maximum and minimum values of the entire subtree subMax=max(max(leftMax,rightMax),root->val); if(!left||!right)//If either the left subtree or the right subtree is not a binary search tree, return false return false; if((root->left==NULL||leftMax<root->val)&&(root->right==NULL||rightMin>root->val))//When the left and right subtrees are not empty and satisfy binary Returns true when looking up the rules of the tree return true; else return false; } bool isValidBST(TreeNode* root) { int leftMin=INT_MAX,leftMax=INT_MIN; return postOrder(root,leftMin,leftMax);//Post-order traversal to calculate whether binary search tree } };