LeetCode题目-173

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2022-03-15 00:21:26

简介 LeetCode题目-173


✏Leetcode之PHP版题目解析(173. Binary Search Tree Iterator)


✏描述

给定一棵搜索二叉树,在搜索二叉树上实现迭代搜索,next返回下一个最小节点


✏题目实例

✏题目分析

说白了其实就是对查找二叉树中序遍历的操作。用一个栈来存储即可。


/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class BSTIterator {
    public $stock=[];
    /**
     * @param TreeNode $root
     */
    function __construct($root) {
        while($root){
            array_unshift($this->stock,$root);
            $root=$root->left;
        }
    }
  
    /**
     * @return the next smallest number
     * @return Integer
     */
    function next() {
        $node=array_shift($this->stock);
        $res=$node->val;
        if($node->right){
            $node=$node->right;
            while($node){
                array_unshift($this->stock,$node);
                $node=$node->left;
            }
        }
        return $res;
    }
  
    /**
     * @return whether we have a next smallest number
     * @return Boolean
     */
    function hasNext() {
        return !empty($this->stock);
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * $obj = BSTIterator($root);
 * $ret_1 = $obj->next();
 * $ret_2 = $obj->hasNext();
 */


转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云