面试题21:如何判断二叉树是搜索二叉树BST?

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 binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution{
public:
    TreeNode* pre = nullptr;
    bool isValidBST(TreeNode* root){
        if(root == nullptr) return true;
        if(!isValidBST(root->left)) return false;
        if(pre && root->val <= pre->val){
            return false;
        }
        pre = root;
        if(!isValidBST(root->right)) return false;
        return true;
    }

};

 

posted @ 2017-05-16 23:19  wxquare  阅读(389)  评论(0编辑  收藏  举报