zoukankan      html  css  js  c++  java
  • leetcode------Binary Search Tree Iterator

    标题: Binary Search Tree Iterator
    通过率: 28.9%
    难度: 中等

    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.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    就是非递归中序遍历二叉树:

    代码如下:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 
    11 public class BSTIterator {
    12     TreeNode node=null;
    13     Stack<TreeNode> stack=new Stack<TreeNode>();
    14     public BSTIterator(TreeNode root) {
    15         if(root!=null){
    16             stack.push(root);
    17             node=root;
    18             while(node.left!=null){
    19                 stack.push(node.left);
    20                 node=node.left;
    21             }
    22         }
    23     }
    24 
    25     /** @return whether we have a next smallest number */
    26     public boolean hasNext() {
    27         if(!stack.isEmpty())return true;
    28         else return false;
    29     }
    30 
    31     /** @return the next smallest number */
    32     public int next() {
    33         node=stack.pop();
    34         int res=node.val;
    35         if(node.right!=null){
    36             stack.push(node.right);
    37             node=node.right;
    38             while(node.left!=null){
    39                 stack.push(node.left);
    40                 node=node.left;
    41             }
    42         }
    43         return res;
    44     }
    45 }
    46 
    47 /**
    48  * Your BSTIterator will be called like this:
    49  * BSTIterator i = new BSTIterator(root);
    50  * while (i.hasNext()) v[f()] = i.next();
    51  */
  • 相关阅读:
    oracle维护表空间和数据文件
    IOS 应用的架构解析
    html5之拖放简单效果
    跟Google学习Android开发-起始篇-与其它应用程序交互(1)
    淘宝服务市场 淘宝订单同步方案
    论文阅读笔记
    页面爬虫(获取其他页面HTML)加载到自己页面
    由href return false 来看阻止默认事件
    Delete it
    Mac上利用Eclipse编译Cocos2d-x
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4363982.html
Copyright © 2011-2022 走看看