Share my non-recursive solution


  • 0
    Y
    bool isValidBST(TreeNode* root)
    {
    	if (root == NULL)
    		return true;
    
    	stack < TreeNode* > DFS;
    	TreeNode* ptr = root;
    	bool isFirst = true;
    	int current;
    	int prev;
    
    	while (!DFS.empty() || ptr)
    	{
    		if (ptr)
    		{
    			DFS.push(ptr);
    			ptr = ptr->left;
    		}
    		else
    		{
    			ptr = DFS.top();
    			DFS.pop();
    			if (isFirst)
    			{
    				current = ptr->val;
    				isFirst = false;
    			}
    			else
    			{
    				prev = current;
    				current = ptr->val;
    				if (current <= prev)
    					return false;
    			}
    			ptr = ptr->right;
    		}
    	}
    
    	return true;
    }
    enter code here

Log in to reply
 

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