C# iterative in-order solution


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        private void PushLeft(Stack<TreeNode> nodes, TreeNode node) {
            var cur = node;
            while(cur != null) { 
                nodes.Push(cur);
                cur = cur.left;
            }
        }
        
        public bool IsValidBST(TreeNode root) {
            var nodes = new Stack<TreeNode>();
            PushLeft(nodes, root);
            TreeNode prev = null;
            while(nodes.Count > 0) { 
                var cur = nodes.Pop();
                if(prev != null && cur.val <= prev.val)
                    return false;
                if(cur.right != null) { 
                    PushLeft(nodes, cur.right);
                }
                prev = cur;
            }
            return true;
        }
    }
    

Log in to reply
 

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