zoukankan      html  css  js  c++  java
  • [LeetCode] 173. Binary Search Tree Iterator Java

    题目:

    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.

    题意及分析:给出一个二叉排序树,求一个该二叉树的遍历器,满足:(1)hasNext()判断树中是否存在一个除了当前数的最小数。 (2)next()返回树中除了当前数的最小数。(3)要求o(1)的时间复杂度和o(h)的空间复杂度。使用一个栈保存即可,初始保存从根节点到最左节点的值,对于next,如果stack非空就存在hasnext smallest number;对于next,下一个最小的就是栈顶的值(因为该栈顶点的左子节点就是当前点,而栈顶点的右子树上的点肯定比栈顶点大),取出栈顶的点,然后对该点的右子节点左上面的操作(即遍历该点到该点的最左叶节点)。

    代码:

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
    
        private Stack<TreeNode> stack;
        public BSTIterator(TreeNode root) {
            stack = new Stack<>();
            TreeNode cur = root;
            while(cur != null){
                stack.push(cur);
                if(cur.left != null)
                    cur = cur.left;
                else
                    break;
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
        	TreeNode node = stack.pop();
            TreeNode cur = node;
            // traversal right branch
            if(cur.right != null){
                cur = cur.right;
                while(cur != null){
                    stack.push(cur);
                    if(cur.left != null)
                        cur = cur.left;
                    else
                        break;
                }
            }
            return node.val;
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */
    

      

  • 相关阅读:
    wepy框架入门
    认识WebStorm-小程序框架wepy
    列表
    透明盒子
    wepy框架滑动组件使用
    底部导航栏效果
    安装less/sass
    wepy快速入门
    实现返回顶部-wepy小程序-前端梳理
    音乐播放器-图片切换-轮播图效果
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7029115.html
Copyright © 2011-2022 走看看