美文网首页
LeetCode173----二叉搜索树迭代器

LeetCode173----二叉搜索树迭代器

作者: 海盗的帽子 | 来源:发表于2019-01-12 20:15 被阅读2次

问题

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

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

示例:

image.png
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

提示:

  • next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
  • 你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。

解法

  • 题目的意思就是放回根据搜索二叉树的排序顺序,迭代返回节点。
  • 首先要了解搜索二叉树的一些特性
    • 对于一个节点,其左孩子比它小,右孩子比它大。
    • 其左右子树都满足搜索二叉树的特性
image.png

以这个图为例:


image.png

总结:

  • 初始化的时候,首先将根节点的左孩子入栈,然后再将其左孩子的左孩子入栈,知道没有左孩子。
  • next 方法,从栈中 pop 出返回,再返回之前判断其右孩子为不为空,不为空就将其右孩子入栈,并从其右孩子开始,将其左孩子入栈,操作和初始化将根节点一样。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {
    TreeNode node ;
    Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        node = root;
        stack = new Stack<>();
        while(node!=null){
            stack.push(node);
            node = node.left;
        }
    }
    
    


    /** @return the next smallest number */
    public int next() {
        int val ;
         node = stack.pop();
        val = node.val;
        node = node.right;
        while(node!=null){
            stack.push(node);
            node = node.left;
        }
        
        return val;
        
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

相关文章

网友评论

      本文标题:LeetCode173----二叉搜索树迭代器

      本文链接:https://www.haomeiwen.com/subject/ecocdqtx.html