A Non recursive solution,very simple and quick


  • 0
    2

    bool isValidBST(TreeNode* root) {
    if(!root) return true;
    int pre,flag=0;
    stack<TreeNode*> st;
    st.push(root);
    TreeNode* p=root;
    p=p->left;
    while(p || !st.empty())
    {
    while(p){ st.push(p); p=p->left; }
    p=st.top();
    st.pop();
    if(flag && p->val<=pre) return false;
    pre=p->val;
    flag=1;
    p=p->right;
    }
    return true;
    }


Log in to reply
 

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