Binary Search Tree Iterator

Design an iterator over a binary search tree with the following rules:
Elements are visited in ascending order (i.e. an in-order traversal)
next() and hasNext() queries run in O(1) time in average.

Example**For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12]
············10
···········/ ···
·········1·····11
···········\······ \
············6 ·····12

题目要求next()返回下一个最小的数,其实不难看出是中序遍历的顺序,二叉树一个性质就是中序遍历是从小到大的递增数列,其实这题就是写一个中序遍历的迭代器。
遍历二叉树有递归和迭代的方法,这题用迭代,当然就要用到stack这种后进先出的数据结构。
代码初始化BSTIterator()的时候就把root和其最左的那条路径上的nodes都放进stack。
next()方法中,我们先取出当前的准备返回的node, 然后check他的右子树是否为空,如果为空当然不用做什么,如果不为空,我们就先把它push到stack里面去,然后遍历它的左子树放进stack。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Example of iterate a tree:
 * BSTIterator iterator = new BSTIterator(root);
 * while (iterator.hasNext()) {
 *    TreeNode node = iterator.next();
 *    do something for node
 * } 
 */
public class BSTIterator {
    //@param root: The root of binary tree.
    
    Stack<TreeNode> stack = new Stack<>();
    public BSTIterator(TreeNode root) {
        // write your code here
        while(root != null) {       //firs push root and all the left most line nodes to stack
            stack.push(root);
            root = root.left;
        }
    }

    //@return: True if there has next node, or false
    public boolean hasNext() {
        // write your code here
        return !stack.isEmpty();
    }
    
    //@return: return next node
    public TreeNode next() {
        // write your code here
        TreeNode node = stack.pop();
        if( node.right != null) {        //if the poped out node has right subtree, we need push the nodes in stack
            
            TreeNode nextPush = node.right;
            stack.push(nextPush);                       //push the right node
            while(nextPush.left != null ) {            // push the left most line of nodes of the right node
                stack.push(nextPush.left);
                nextPush = nextPush.left;
            }
        }
        
        return node;
    }
}
    原文作者:Leonlong
    原文地址: https://www.jianshu.com/p/2c74f2209688
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞