[leetCode刷题笔记]173. Binary Search Tree Iterator

来源:互联网 发布:sql最后一行加合计行 编辑:程序博客网 时间:2024/06/07 01:16

用stack来存储node,先存储最左边的node,再往右移动

public class BSTIterator {    Stack<TreeNode> stack = new Stack();    public BSTIterator(TreeNode root) {        pushLeft(root);    }    /** @return whether we have a next smallest number */    public boolean hasNext() {        return !stack.isEmpty();    }    /** @return the next smallest number */    public int next() {        TreeNode curr = stack.pop();        pushLeft(curr.right);        return curr.val;    }    /** push all left node for a node */    private void pushLeft(TreeNode node) {        for (; node != null;) {            stack.push(node);            node = node.left;        }    }}



0 0
原创粉丝点击