173. Binary Search Tree Iterator

一、题目

  1、审题

 

  2、分析

    给出一棵二分查找树的根节点。实现 next() 方法返回下一个最小的二叉树的节点值。 hasNext() 判断是否还有值。

 

二、解答

  1、思路:

    采用一个 Stack 存储二叉查找树的左斜子树节点值。

    next() 方法返回栈顶节点值,并将其右孩子的左斜子树入栈即可。

    hashNext() 根据栈是否为空即可。

public class BSTIterator {

    private Stack<TreeNode> stack = new Stack<TreeNode>();

    public BSTIterator(TreeNode root) {
        pushAll(root);
    }

    private void pushAll(TreeNode root) {
        while(root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode tmpNode = stack.pop();
        pushAll(tmpNode.right);
        return tmpNode.val;
    }
}

 

posted @ 2018-10-16 20:53  skillking2  阅读(78)  评论(0编辑  收藏  举报