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.

  思路:中序遍历的结果正好是二分查找树对应的数据的顺序,所以先中序遍历数据,然后检查遍历的结果是不是递增的

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    bool check(vector<int> &a)

    {

        if(a.size() == 1) return true;

        for(int i = 1; i< a.size(); i++)

          if(a[i] <= a[i-1])

                return false;

        return true;

   }

    bool isValidBST(TreeNode *root) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(root == NULL ) return true ;

        vector<int> inorder ;

        stack<TreeNode *> myS;

       // myS.push(root);

        TreeNode *p = root;

        while(!myS.empty()||p){

           while(p){

             myS.push(p);

             p = p->left;

           }

           p = myS.top();myS.pop();

           inorder.push_back(p->val) ;

           p = p->right ;

        }

        

        return check(inorder) ;

        

    }

};

 改进版本:访问每个数据的时候就进行检查,奇怪的是小数据时时间减小一半,大数据竟然比上面的用时还要多

 bool isValidBST(TreeNode *root) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(root == NULL ) return true ;



        stack<TreeNode *> myS;

       // myS.push(root);

        TreeNode *p = root;

        int flag = 0;

        int value ;

        while(!myS.empty()||p){

           while(p){

             myS.push(p);

             p = p->left;

           }

           p = myS.top();

           myS.pop();

          

           if(flag){

               

              if( p->val <= value)

                  return false;

               

           }else{

               

               flag = 1;

             

           }

           value  = p->val;

           p = p->right ;

        }

        return true ;

        

    }

 

你可能感兴趣的:(Binary search)