Home > Article > Backend Development > Teach you how to verify a binary search tree quickly and accurately (code example)
The content of this article is about teaching you how to verify a binary search tree quickly and accurately. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { return isValidBST(root, nullptr, nullptr); } bool isValidBST(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) { //此节点不存在,返回true if (!root) return true; //此结点比最大值要大或者比最小值要小. if (minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val) return false; //继续判断左边或者右边,判断左边的时候传入最大值为root,判断右边的时候传入最小值为root return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode); } };
The above is the detailed content of Teach you how to verify a binary search tree quickly and accurately (code example). For more information, please follow other related articles on the PHP Chinese website!