What if root is null?


  • 0
    Q

    I use C# to answer all the questions and one of the test cases is root = null.
    Tried many cases and here is the solution:

    public class BSTIterator {
        public Stack<TreeNode> _mystack = new Stack<TreeNode>(); 
        
        public BSTIterator(TreeNode root)
        {
            
            if(root != null) {
                findMostLeftNode(root, _mystack);
            }
            
        }
    
        /** @return whether we have a next smallest number */
        public bool HasNext()
        {
            return _mystack.Count > 0;
        }
    
        /** @return the next smallest number */
        public int Next()
        {
            if (_mystack.Count == 0) {
                return 0;
            }
            var top = _mystack.Pop();
            if (top.right != null) {
                findMostLeftNode(top.right, _mystack);
            }
            return top.val;
        }
    
        private void findMostLeftNode(TreeNode root, Stack<TreeNode> mystack)
        {
            while (root != null)
            {
                mystack.Push(root);
                root = root.left;
            }
        }
    

    }


Log in to reply
 

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