• [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();
     */
    

      

  • 相关阅读:
    找工作就上智联,效果真快,然而让我去的公司都是泡我呢
    只能面深度学习岗和算法岗,其他都不会
    2维矩阵前缀和技巧题目
    计算机基础背诵
    集合函数AVG,SUM,MAX,MIN
    集合函数COUNT
    修改删除数据记录
    多表查询
    查询数据表中的记录
    SQL基本语句(3) LOAD DATA INFILE
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7029115.html
Copyright © 2020-2023  润新知