LeetCode 173. Binary Search Tree Iterator

来源:互联网 发布:centos加固 编辑:程序博客网 时间:2024/06/14 16:33
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    TreeNode root;Stack<TreeNode> stack = new Stack<TreeNode>();    public BSTIterator(TreeNode root) {        this.root = root;        TreeNode tn = root;        while (tn != null) {        stack.push(tn);        tn = tn.left;        }    }    /** @return whether we have a next smallest number */    public boolean hasNext() {        return !stack.isEmpty();    }    /** @return the next smallest number */    public int next() {        TreeNode tn = stack.pop();    int val = tn.val;        if (tn.right != null) {        tn = tn.right;        while (tn != null) {            stack.push(tn);            tn = tn.left;            }        }        return val;    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */

0 0
原创粉丝点击