Cover image for Interview Classic 150 Problem P98: Validate Binary Search Tree

Interview Classic 150 Problem P98: Validate Binary Search Tree


Timeline

Timeline

2025-10-31

init

Inorder traversal

Problem:

In-order traversal must be strictly increasing.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
struct TreeNode {	int val;	TreeNode *left;	TreeNode *right;	TreeNode()		: val(0)		, left(nullptr)		, right(nullptr)	{	}	TreeNode(int x)		: val(x)		, left(nullptr)		, right(nullptr)	{	}	TreeNode(int x, TreeNode *left, TreeNode *right)		: val(x)		, left(left)		, right(right)	{	}};#include <stack>#include <climits>using std::stack;class Solution {    public:	bool isValidBST(TreeNode *root)	{		stack<TreeNode *> st;		TreeNode *p = root, *left, *right;		long long last = LONG_MIN;		while (p || !st.empty()) {			if (p) {				st.push(p);				p = p->left;			} else {				// visit				p = st.top();				st.pop();				if (p->val <= last) {					return false;				}				last = p->val;				p = p->right;			}		}		return true;	}};

leetcode hot 100 rewrite

1234567891011121314151617181920212223242526272829
#include <stack>using std::stack;class Solution {    public:        bool isValidBST(TreeNode *root)        {                // The in-order traversal sequence is sorted.                stack<TreeNode *> stk;                TreeNode *p = root, *last = nullptr;                while (p || !stk.empty()) {                        if (p) {                                stk.push(p);                                p = p->left;                        } else {                                p = stk.top();                                stk.pop();                                // visit p                                if (last && p->val <= last->val)                                        return false;                                last = p;                                p = p->right;                        }                }                return true;        }};
Loading comments…