LeetCode Binary Search Tree Iterator

原创 2015年01月01日 08:40:46

给了一个BST的根节点,要求写一个遍历类,将这棵树从小到大遍历一遍。

我的做法是先把BST遍历一遍, 然后放到数组里,这样看起来似乎题目很简单。


public class BSTIterator {
	int len = 0, index = 0;
	int[] arr = new int[1000000];

	public BSTIterator(TreeNode root) {
		search(root);
		len = index;
		index = 0;
	}

	public void search(TreeNode f) {
		if (f == null) 
			return;
		search(f.left);
		arr[index++] = f.val;
		search(f.right);
	}

	/** @return whether we have a next smallest number */
	public boolean hasNext() {
		if (index == len)
			return false;
		return true;
	}

	/** @return the next smallest number */
	public int next() {
		return arr[index++];
	}

}





相关文章推荐

《leetCode》:Binary Search Tree Iterator

Binary Search Tree Iterator题目如下:Implement an iterator over a binary search tree (BST). Your iterator...

<LeetCode OJ> 173. Binary Search Tree Iterator

Total Accepted: 50775 Total Submissions: 144066 Difficulty: Medium Implement an iterator over a...

[leetcode]Binary Search Tree Iterator

Binary Search Tree Iterator   Implement an iterator over a binary search tree (BST). Your it...

[LeetCode]173.Binary Search Tree Iterator

【题目】 Implement an iterator over a binary search tree (BST). Your iterator will be initialized with...

leetcode-173:Binary Search Tree Iterator(Java)

Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterato...

LeetCode-Binary Search Tree Iterator-解题报告

原题链接https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary ...

LeetCode | Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro...

LeetCode Binary Search Tree Iterator

在一棵二叉搜索树上实现一个迭代器,初始化参数为该二叉搜索树的根节点。当调用迭代器的next()方法时,返回该二叉搜索树中最小的元素。...

LeetCode173-Binary Search Tree Iterator

LeetCode 173 : Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Yo...

Leetcode:Binary Search Tree Iterator

最近真是各种私事,也顺便给自己懒惰的机会了。今天开始要继续坚持! 看了这道题,顿时觉得自己太挫,Binary Search Tree居然不知道什么意思。赶紧百度搜索了下。下面这篇文章其实就挺简单易...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Binary Search Tree Iterator
举报原因:
原因补充:

(最多只允许输入30个字)