【LeetCode】Validate Binary Search Tree

来源:互联网 发布:java常用的框架有哪些 编辑:程序博客网 时间:2024/04/29 21:42
/** * 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 isValidBST(TreeNode *root) {    stack<TreeNode*> s;       TreeNode* p = root;    TreeNode* pre = NULL;   // pre保持为p的中序前驱    while(p || !s.empty())    {        if(p)        {            s.push(p);            p = p->left;        }        else        {            p = s.top(); s.pop();            if( pre && (p->val <= pre->val) )  return false;  // 不是二叉排序树            pre = p;   // 记下前驱结点            p = p->right;        }    }    return true;  // 二叉排序树    }};

0 0