leetcode : 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.

很明显的中根遍历,可以以一个引用一直保存是否为BST,但是注意的是只能由true状态变为false,不能由false变成true。

比如左子树不是BST,那么可以ret就变成true,但是如果右子树是BST,不能将这个状态变回true

PS: 凡是涉及到指针果真很容易就非法引用了。。。

AC代码:

class Solution {
public:
    bool isValidBST(TreeNode *root) {
        bool ret = true;
        TreeNode *pre = NULL;
        if(root)
            inorder(root, pre, ret);
        return ret;
    }
    void inorder(TreeNode *root, TreeNode *&pre, bool &ret){
        if(ret == false)
            return;
        if(root->left)
            inorder(root->left, pre, ret);
            
        if(!pre)
            pre = root;
        else{
            ret = ret ? root->val > pre->val : ret;
            pre = root;
        }
        
        if(root->right)
            inorder(root->right, pre, ret);
    }
};

 

posted on 2014-11-24 10:32  远近闻名的学渣  阅读(139)  评论(0)    收藏  举报

导航