Leetcode 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.

/**
 * 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) {

        // v.size() == 0 
        if (root == nullptr) return true;     
        vector<int> v;
        read(root, v);
        size_t i = 1;

        for(; i != v.size(); ++i) {
            if (v[i] <= v[i - 1])
                break;
        }
        return i == v.size();   
    }

// 遍历
     void read(TreeNode* root, vector<int>& v) {
         if (root == nullptr) return;
         read(root->left, v);
         v.push_back(root->val);
         read(root->right, v);
     }
};
/**
 * 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) {

        // v.size() == 0 
        if (root == nullptr) return true;     
        vector<long> v(1, long(INT_MIN) - 1);
        return read(root, v);
    }

// 遍历
     bool read(TreeNode* root, vector<long>& v) {
         if (root == nullptr) return true;
         if (read(root->left, v) == false) return false;
         if (root-> val <= v[v.size() - 1]) return false;
         v.push_back(root->val);
         return read(root->right, v);
     }
};

参考后

/**
 * 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) {
        TreeNode* p = root;
        stack<TreeNode*> s;
        long lastVal = long(INT_MIN) - 1;

        while (p != nullptr || !s.empty()) {       
            if (p != nullptr) {
                s.push(p);
                p = p->left;
            }
            else {
                p = s.top();
                s.pop();
                if (lastVal >= p->val) return false;
                lastVal = p->val;
                p = p->right;
            }
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值