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

来源:互联网 发布:centos svn 防火墙 编辑:程序博客网 时间:2024/06/15 20:13

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.



#题解


/**
 * 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:
中序遍历




0 0