Home > Backend Development > PHP Tutorial > Teach you how to verify a binary search tree quickly and accurately (code example)

Teach you how to verify a binary search tree quickly and accurately (code example)

坏嘻嘻
Release: 2023-04-04 07:52:01
Original
2051 people have browsed it

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.

TitleTeach you how to verify a binary search tree quickly and accurately (code example)

Code

/**
 * 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);
     }
};
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template