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


    通过一个优先队列进行存储数据 然后每一次读数据都是输出第一个结点

    class BSTIterator {
    	Queue<Integer>ls = new PriorityQueue<Integer>();
    
    	public BSTIterator(TreeNode root) {
            dfs(root);
    	}
    	public void dfs(TreeNode root) {
    		if(root==null) {return ;}
    		ls.add(root.val);
    		if(root.left!=null)dfs(root.left);
    		if(root.right!=null)dfs(root.right);
    	}
    	/** @return the next smallest number */
    	public int next() {
    		return ls.poll();
    	}
    
    	/** @return whether we have a next smallest number */
    	public boolean hasNext() {
    		if(ls.size() == 0)
    			return false;
    		else return true;
    	}
    }
    
    

    中序遍历+栈模拟

    class BSTIterator {
    	Stack<TreeNode> stack = new Stack<TreeNode>();
        public BSTIterator(TreeNode root) {
        	stack.clear();
        	while(root!=null) {
        		stack.add(root);
        		root = root.left;
        	}
        }
        
        /** @return the next smallest number */
        public int next() {
            TreeNode p = stack.pop();
            int res = p .val;
            p = p.right;
            while(p!=null) {
            	stack.add(p);
            	p = p.left;
            }
            return res;
        }
        
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
    }
    
  • 相关阅读:
    全端开发必备!10个最好的 Node.js MVC 框架
    action和servlet的关系
    js模块化
    前端类库
    Windows下配置nginx+php(wnmp)
    DllMain的作用
    在linux上实现DllMain + 共享库创建方法
    QT实现Windows下DLL程序编写
    平台相关的宏
    远程线程的注入 PE的修正
  • 原文地址:https://www.cnblogs.com/cznczai/p/11363169.html
Copyright © 2011-2022 走看看