本文共 1126 字,大约阅读时间需要 3 分钟。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */class BSTIterator { private Listlist; private int index; public BSTIterator(TreeNode root) { this.list = new ArrayList<>(); this.index = -1; this.inOrder(root); } private void inOrder(TreeNode root) { if(root == null) { return; } inOrder(root.left); list.add(root.val); inOrder(root.right); } public int next() { return this.list.get(++index); } public boolean hasNext() { return (this.index + 1) < list.size(); }}/** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
转载地址:http://glhzi.baihongyu.com/