LeetCode/Validate Binary Search Tree

Problem Summary

Given a binary tree, determine if it is a binary search tree.

Solution

I have wrote about this problem before: https://suzyz.github.io/2017/10/14/validate-binary-search-tree/

Now I would like to implement Solution 2 in that post. That is, carry out an inorder traversal with the help of a stack.

It is relatively harder to code, but not much work actually.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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) {
stack<TreeNode *> st;
TreeNode *pre = NULL;
while (root != NULL || !st.empty())
{
while (root != NULL)
{
st.push(root);
root = root->left;
}
TreeNode *cur = st.top();
st.pop();
if (pre != NULL && cur->val <= pre->val)
return false;
pre = cur;
root = cur->right;
}
return true;
}
};