星空网 > 软件开发 > Java

[LeetCode] Binary Search Tree Iterator

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.

 

     中午下雨了。于是木有吃午饭(=。=)现在有点饿。

     这个比较难的就是next() method了,就是喊你返回BTS中最小的那个数。

     然后很容易的,我们要先建一个不管是List,stack还是神马的,反正拿来store每个结点最小的数就行了。(一般情况下就是最左边的那个数)

     当然呢如果最左边刚好null呢?我们第一次store的时候就肯定会在这里停下了,因此我们需要检查右边是否null,如果右边不是null的,那么就检查这个右边的treenode左边是否null,如果是,继续接着往下…………

      代码如下。~

      

/** * Definition for binary tree * public class TreeNode { *   int val; *   TreeNode left; *   TreeNode right; *   TreeNode(int x) { val = x; } * } */public class BSTIterator {  List<TreeNode> tree;  public BSTIterator(TreeNode root) {    tree=new ArrayList<TreeNode>();    while(root!=null){      tree.add(root);      root=root.left;    }      }  /** @return whether we have a next smallest number */  public boolean hasNext() {    return !tree.isEmpty();  }  /** @return the next smallest number */  public int next() {    TreeNode min=tree.remove(tree.size()-1);    TreeNode temp=min.right;    while(temp!=null){      tree.add(temp);      temp=temp.left;    }    return min.val;  }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */

 




原标题:[LeetCode] Binary Search Tree Iterator

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

独立站品牌案例⑰:美甲独立站爆红海外,TikTok浏览量破亿:https://www.kjdsnews.com/a/1446227.html
一手赏析雅虎Yahoo广告投放类型介绍!:https://www.kjdsnews.com/a/1446228.html
互联网医疗之好大夫分析:https://www.kjdsnews.com/a/1446229.html
卖家注意!6月起TikTok Shop印尼站迎来调整!:https://www.kjdsnews.com/a/1446230.html
Temu出“最狠”竞价新政!未参与产品或被下架:https://www.kjdsnews.com/a/1446231.html
AI广告行业的16个重构:https://www.kjdsnews.com/a/1446232.html
请问西安及周边5日游怎么安排?:https://www.vstour.cn/a/364173.html
图策全国免景点门票 预订景区门票优惠:https://www.vstour.cn/a/364174.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流