leetcode java Binary Search Tree Iterator

来源:互联网 发布:阿里集团股份构成知乎 编辑:程序博客网 时间:2024/06/03 10:01
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    private List<Integer> pre;private int curIndex;public BSTIterator(TreeNode root){pre = new ArrayList<Integer>();curIndex = 0;preTraverse(root);}private void preTraverse(TreeNode root){Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode tmp = root;while(tmp != null){stack.add(tmp);tmp = tmp.left;}while(stack.size() > 0){tmp = stack.pop();pre.add(tmp.val);if(tmp.right != null){TreeNode t = tmp.right;//stack.add(t);while(t !=null){stack.add(t);t = t.left;}}}}/** @return whether we have a next smallest number */    public boolean hasNext() {    if(curIndex < pre.size()){    return true;    }        return false;    }    /** @return the next smallest number */    public int next() {        int res = pre.get(curIndex);        curIndex++;        return res;    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */

0 0
原创粉丝点击