1. 程式人生 > >173. Binary Search Tree Iterator

173. Binary Search Tree Iterator

arc eth 返回 return bsp next image 二叉樹 nbsp

一、題目

  1、審題

技術分享圖片

 

  2、分析

    給出一棵二分查找樹的根節點。實現 next() 方法返回下一個最小的二叉樹的節點值。 hasNext() 判斷是否還有值。

二、解答

  1、思路:

    采用一個 Stack 存儲二叉查找樹的左斜子樹節點值。

    next() 方法返回棧頂節點值,並將其右孩子的左斜子樹入棧即可。

    hashNext() 根據棧是否為空即可。

public class BSTIterator {

    private Stack<TreeNode> stack = new Stack<TreeNode>();

    
public BSTIterator(TreeNode root) { pushAll(root); } private void pushAll(TreeNode root) { while(root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() {
return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode tmpNode = stack.pop(); pushAll(tmpNode.right); return tmpNode.val; } }

173. Binary Search Tree Iterator