Binary Search Tree Iterator

来源:互联网 发布:汝窑茶具 淘宝 编辑:程序博客网 时间:2024/05/22 06:07

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


接着上一题,这题考察的是中序遍历。用的方法跟上面那道题的思路是相同的。

中序遍历的思路是使用一个栈,将它以及它的左孩子压入栈。每次弹栈的时候,判断是否存在右孩子,如果存在的话,对右孩子进行相同的操作,把右孩子以及右孩子的左孩子压入栈。

代码:

Stack<TreeNode> stack;    TreeNode root;    public BSTIterator(TreeNode root) {        stack = new Stack<>();        this.root = root;        //init the stack by pushing left nodes into the stack        pushToStack(root);    }    private void pushToStack(TreeNode node){        if(node == null) return;        stack.push(node);        while(node.left != null){            node = node.left;            stack.push(node);        }    }    /** @return whether we have a next smallest number */    public boolean hasNext() {        return !stack.isEmpty();    }    /** @return the next smallest number */    public int next() {        //needs null pointer handling        if(!hasNext()) return -1;        TreeNode node = stack.pop();        if(node.right!= null){            pushToStack(node.right);        }        return node.val;    }


0 0