LeetCode|Binary Search Tree Iterator-java

来源:互联网 发布:火石软件 编辑:程序博客网 时间:2024/06/17 00:14

题目:

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.

思路:

对二叉搜索树进行迭代输出,java中的LinkedList实现了队列,首先,中序遍历将节点存入队列中,再将队列从头部输出。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    private LinkedList<TreeNode> linkedList;        public BSTIterator(TreeNode root) {            linkedList = new LinkedList<>();            middleOrder(root, linkedList);        }        private void middleOrder(TreeNode node, LinkedList<TreeNode> linkedList) {            if (node == null) {                return;            }            middleOrder(node.left, linkedList);            linkedList.addLast(node);            middleOrder(node.right, linkedList);        }        /**         * @return whether we have a next smallest number         */        public boolean hasNext() {            return linkedList != null && !linkedList.isEmpty();        }        /**         * @return the next smallest number         */        public int next() {            return linkedList.removeFirst().val;        }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */



0 0
原创粉丝点击