zoukankan      html  css  js  c++  java
  • 173. Binary Search Tree Iterator

    一、题目

      1、审题

     

      2、分析

        给出一棵二分查找树的根节点。实现 next() 方法返回下一个最小的二叉树的节点值。 hasNext() 判断是否还有值。

    二、解答

      1、思路:

        采用一个 Stack 存储二叉查找树的左斜子树节点值。

        next() 方法返回栈顶节点值,并将其右孩子的左斜子树入栈即可。

        hashNext() 根据栈是否为空即可。

    public class BSTIterator {
    
        private Stack<TreeNode> stack = new Stack<TreeNode>();
    
        public BSTIterator(TreeNode root) {
            pushAll(root);
        }
    
        private void pushAll(TreeNode root) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode tmpNode = stack.pop();
            pushAll(tmpNode.right);
            return tmpNode.val;
        }
    }
  • 相关阅读:
    四则运算
    androidstdio导入工程报错
    日程代码任务1
    软件团队模式选择
    初识软件工程
    java数组中最大的子数组之和
    解决键盘布局错误(日文系统)
    固态硬盘的更替
    ZendDebugger的配置
    apache命令行启动
  • 原文地址:https://www.cnblogs.com/skillking/p/9800574.html
Copyright © 2011-2022 走看看