Home  >  Article  >  Backend Development  >  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)

坏嘻嘻
坏嘻嘻Original
2018-09-15 10:04:111981browse

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);
     }
};

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!

Statement:
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