173Binary Search Tree Iterator

来源:互联网 发布:淘宝店上传图片的大小 编辑:程序博客网 时间:2024/09/21 06:33

题目链接:https://leetcode.com/problems/binary-search-tree-iterator/

题目:

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.

解题思路:
这题的考点是二叉搜索树的遍历->二叉树的中序遍历
将中序遍历拆分成三个动作,初始化,hasNext 和 next。
1. 构造器完成的动作是,一直往树的左下查找,将经过的结点压入栈中,直至找到该二叉树最左下的结点,即该二叉搜索树最小的结点。
2. hasNext完成的动作是,判断栈是否为空。栈顶元素始终保持当前欲访问的最小结点。
3. next完成的动作是,弹栈获取当前最小元素,返回该元素值之前,将该元素右孩子作为根结点,向其子树中左下遍历,将经过的结点入栈,类似初始化的工作。使栈顶元素始终保持当前欲访问的最小结点。

代码实现:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    private TreeNode iterRoot;    private LinkedList<TreeNode> stack = new LinkedList();    public BSTIterator(TreeNode root) {        this.iterRoot = root;        while(iterRoot != null) {            stack.push(iterRoot);            iterRoot = iterRoot.left;        }    }    /** @return whether we have a next smallest number */    public boolean hasNext() {        if(!stack.isEmpty())            return true;        else            return false;    }    /** @return the next smallest number */    public int next() {        TreeNode tmp = stack.pop();        if(tmp.right != null) {            iterRoot = tmp.right;            while(iterRoot != null) {                stack.push(iterRoot);                iterRoot = iterRoot.left;            }        }        return tmp.val;    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
61 / 61 test cases passed.Status: AcceptedRuntime: 6 ms
0 0
原创粉丝点击