zoukankan      html  css  js  c++  java
  • 173.二叉搜索树迭代器

    2020-05-29
    二叉搜索树迭代器

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

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

    题解:
    思路1:二叉树的中序遍历
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     */
    var BSTIterator = function (root) {
      this.arr = [];
      this.index = 0;
      let handler = (node) => {
        if(!node) return;
        handler(node.left);
        this.arr.push(node.val);
        handler(node.right);
      }
      handler(root);
    };
    
    /**
     * @return the next smallest number
     * @return {number}
     */
    BSTIterator.prototype.next = function () {
      return this.arr[this.index++];
    };
    
    /**
     * @return whether we have a next smallest number
     * @return {boolean}
     */
    BSTIterator.prototype.hasNext = function () {
      return this.index <= this.arr.length;
    };
    
    /**
     * Your BSTIterator object will be instantiated and called as such:
     * var obj = new BSTIterator(root)
     * var param_1 = obj.next()
     * var param_2 = obj.hasNext()
     */
  • 相关阅读:
    oracle 函数
    Oracle 语句
    递归算法算出某个目录下所有目录和文件
    static
    递归算法
    JVM/JDK/JRE
    java跨平台原理
    .NET 未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”
    JS 判断对象是否为空
    html网页打印A4样式
  • 原文地址:https://www.cnblogs.com/lanpang9661/p/12985514.html
Copyright © 2011-2022 走看看