Leetcode 98 Validate Binary Search Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010821666/article/details/82749486

Leetcode 98 Validate Binary Search Tree

#include <stack>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left,*right;
    TreeNode(int x):val(x),left(NULL),right(NULL){}
};

class Solution{

public:
    bool isValidBST(TreeNode *root){

        stack<TreeNode*> path;
        if(!root || (!root->right && !root->left))
            return true;
        TreeNode* node = root;
        long lastNum = INT64_MIN ;//attention
        while(node || !path.empty()){
            while(node) {
                path.push(node);
                node = node->left;
            }
            if(!node) {
                node = path.top();
                path.pop();
                int curNum = node->val;
                if (curNum <= lastNum)
                    return false;
                lastNum = curNum;
                node = node->right;
            }
        }
        return true;

    }
};

猜你喜欢

转载自blog.csdn.net/u010821666/article/details/82749486