力扣173.二叉搜索树迭代器

173.二叉搜索树迭代器

思路:

本题比较简单,中序遍历用链表保存节点值,并按照题意进行写代码即可

代码实现
/**
 * 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 {
    
    List<Integer> list = new LinkedList<Integer>();
	int i = 0;
	public BSTIterator(TreeNode root) {
        inorder(root, list);
    }
    
    public int next() {
    	return list.get(i++);
    }
    
    public boolean hasNext() {
    	return i < list.size();
    }
    
    public void inorder(TreeNode root, List<Integer> list) {
    	if (root == null) return;
    	
    	inorder(root.left, list);
    	list.add(root.val);
    	inorder(root.right, list);
    }

}

/**
 * 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();
 */

你可能感兴趣的:(leetcode,链表,数据结构)