[理解leetcode解法]98. Validate Binary Search Tree 判断是否二分查找树

98. Validate Binary Search Tree 判断是否二分查找树


#题目

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.



#题解
[理解leetcode解法]98. Validate Binary Search Tree 判断是否二分查找树_第1张图片

/**
 * 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 {
private:
    TreeNode* pre;    
public:
    bool isValidBST(TreeNode* root) {
        if(root != NULL){
            if(!isValidBST(root->left)){
                return false;
            }
            if(pre != NULL && root -> val <= pre -> val ) return false;   //1
            pre=root;
            if(!isValidBST(root->right)){
                return false;
            }
            return true;
        }
        return true;
    }
};

#题释
//1:
中序遍历




你可能感兴趣的:([理解leetcode解法]98. Validate Binary Search Tree 判断是否二分查找树)