码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator

时间:2019-12-22 00:54:29      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:pre   -o   rsa   wrapper   else   for   visit   需要   eth   

Description

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

Example 1

Input:  {10,1,11,#,6,#,12}
Output:  [1, 6, 10, 11, 12]
Explanation:
The BST is look like this:
  10
  / 1 11
  \     6  12
You can return the inorder traversal of a BST [1, 6, 10, 11, 12]
/**
 * 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 {
    private Stack<TreeNode> stack = new Stack<>();
    
    // @param root: The root of binary tree.
    public BSTIterator(TreeNode root) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }

    //@return: True if there has next node, or false
    public boolean hasNext() {
        return !stack.isEmpty();
    }
    
    //@return: return next node
    public TreeNode next() {
        TreeNode curt = stack.peek();
        TreeNode node = curt;
        
        // move to the next node
        if (node.right == null) {
            node = stack.pop();
            while (!stack.isEmpty() && stack.peek().right == node) {
                node = stack.pop();
            }
        } else {
            node = node.right;
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
        }
        
        return curt;
    }
}

  

Example 2

Input: {2,1,3}
Output: [1,2,3]
Explanation:
The BST is look like this:
  2
 / 1   3
You can return the inorder traversal of a BST tree [1,2,3]

Challenge

Extra memory usage O(h), h is the height of the tree.

Super Star: Extra memory usage O(1)

 

思路:

这是一个非常通用的利用 stack 进行 Binary Tree Iterator 的写法。

stack 中保存一路走到当前节点的所有节点,stack.peek() 一直指向 iterator 指向的当前节点。
因此判断有没有下一个,只需要判断 stack 是否为空
获得下一个值,只需要返回 stack.peek() 的值,并将 stack 进行相应的变化,挪到下一个点。

挪到下一个点的算法如下:

  1. 如果当前点存在右子树,那么就是右子树中“一路向西”最左边的那个点
  2. 如果当前点不存在右子树,则是走到当前点的路径中,第一个左拐的点

访问所有节点用时O(n),所以均摊下来访问每个节点的时间复杂度时O(1)

 

Binary Search Tree Iterator

标签:pre   -o   rsa   wrapper   else   for   visit   需要   eth   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!