LeetCode(173):二叉搜索树迭代器 Binary Search Tree Iterator(Java)

2019.11.16 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

数据结构题。

要求实现一个二叉搜索树的迭代器,实际上依靠一个栈即可实现。构造迭代器时,从根节点遍历至最左结点(最小起始节点),并将左侧遍历的元素全部入栈。

每次访问next(),将栈顶元素出栈并返回,将其右子树的所有左侧结点入栈。


传送门:二叉搜索树迭代器

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.

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

示例:

    7
   / \
  3  15
     / \
    9   20

BSTIterator iterator = new BSTIterator(root);
iterator.next();    // 返回 3
iterator.next();    // 返回 7
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 9
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 15
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 20
iterator.hasNext(); // 返回 false


import java.util.Stack;

你可能感兴趣的:(JAVA,LeetCode,数据结构与算法,数据结构与算法,LeetCode,迭代器,数据结构,二叉树)