C# Iterative solution


  • 0
    S
    using System.Collections.Generic;
    public class Solution {
        public bool IsValidBST(TreeNode root) {
            Stack<TreeNode> nodeStack = new Stack<TreeNode>();
    		AddLeftRootNodesToStack(nodeStack, root);
    		TreeNode prev = null;
    		while(nodeStack.Count!=0 && (prev==null || prev.val < nodeStack.Peek().val)){
    			prev = nodeStack.Pop();
                if(prev.right!=null)
    			AddLeftRootNodesToStack(nodeStack, prev.right);
    		}
    		
    		return nodeStack.Count == 0;
        }
    	
    	private void AddLeftRootNodesToStack(Stack<TreeNode> nodeStack, TreeNode node) {
    		while(node!=null) {
    			nodeStack.Push(node);
    			node = node.left;
    		}
    	}
    }```

Log in to reply
 

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