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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

思路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 {
public:
    bool isValidBST(TreeNode* root) {
        stack<TreeNode *> s;
        int before;
        bool once=true;
        while(!s.empty()||root){
            while(root){
                s.push(root);
                root=root->left;
            }
            TreeNode *cur=s.top();
            s.pop();
            if(once){
                once=false;
            }
            else if(before>=cur->val)
                return false;
            before=cur->val;
            root=cur->right;
        }
        return true;
    }
};

思路2:dfs,要保证树中的每一个节点都满足在左右边界范围之内。请注意,初始化时不能设置左右边界为INT_MIN,INT_MAX,因为给到的测试案例中有这两个数,为此不得不启用long类型,并设min=INT_MIN-1,max=INT_MAX+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 {
     
     bool check(TreeNode *node, long min, long max)
     {
         if (!node)
             return true;
         long val=node->val;
         return   val>min&&val<max&&check(node->left,min,val)&&check(node->right,val,max);    
        
     }
public:
    bool isValidBST(TreeNode* root) {
        long min=INT_MIN;
        min--;
        long max=INT_MAX;
        max++;
        return check(root,min,max);
    }
};

 

posted @ 2016-03-06 16:19  ZHOU YANG  阅读(333)  评论(0编辑  收藏  举报