C# Accepted solution using list


  • 0
    J
    public BSTIterator(TreeNode root) 
        {
            Helper(root);
        }
        
        List<int> list = new List<int>();
        int index = 0;
        
        private void Helper(TreeNode root)
        {
            if (root == null) return;
            Helper(root.left);
            list.Add(root.val);
            Helper(root.right);
        }
    
        /** @return whether we have a next smallest number */
        public bool HasNext() 
        {
            if (list.Count == 0) return false;
            return (index < list.Count);
        }
    
        /** @return the next smallest number */
        public int Next() 
        {
            var result = list[index];
            index++;
            return result;    
        }
    

Log in to reply
 

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