My iterative c++ solution


  • 0
    C
    class Solution {
    public:
    bool isValidBST(TreeNode* root) {
        if(root == NULL || (root->left == NULL && root->right == NULL))
        {
            return true;
        }
        stack<TreeNode*> st;
        TreeNode* tn = root;
        int pre = INT_MIN;
        bool first = true;
        while(tn != NULL || !st.empty())
        {
            if(tn != NULL)
            {
                st.push(tn);
                tn = tn->left;
            }
            else
            {
                tn = st.top();
                if(first || tn->val > pre)
                {
                    pre = tn->val;
                    first = false;
                }
                else
                {
                    return false;
                }
                tn = tn->right;
                st.pop();
            }
        }
        return true;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.