[算法分析与设计] leetcode 每周一题: Validate Binary Search Tree

题目链接:https://leetcode.com/problems/validate-binary-search-tree/discuss/


题目:


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   3
Binary tree  [2,1,3], return true.

Example 2:

    1
   / \
  2   3
Binary tree  [1,2,3], return false.
思路:

在二叉搜索树中每一个节点都可能存在约束,都有可能存在一个比该节点大的节点以及一个比该节点小的点,因此用递归,每次传入一个当前结点,极大点,极小点,比较即可。


代码:

class Solution {
public:

    bool judgeValid(TreeNode * curNode, TreeNode* minNode, TreeNode* maxNode) {
       if(!curNode) return true;
       if(minNode && minNode->val >= curNode->val || maxNode && maxNode->val <= curNode->val){
           return false;
       }
       return judgeValid(curNode->left, minNode, curNode) && judgeValid(curNode->right, curNode, maxNode);
    }
    bool isValidBST(TreeNode* root) {
        return judgeValid(root, nullptr, nullptr);
       
        
    }
};


猜你喜欢

转载自blog.csdn.net/liangtjsky/article/details/78898206