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-173:Binary Search Tree Iterator(Java)

Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterato...
  • wen1158646729
  • wen1158646729
  • 2015-08-18 10:58:59
  • 1209

leetcode 173: Binary Search Tree Iterator

Binary Search Tree Iterator Total Accepted: 1141 Total Submissions: 3857 Implement an iterat...
  • xudli
  • xudli
  • 2015-01-02 12:44:56
  • 4142

Leetcode: Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro...
  • doc_sgl
  • doc_sgl
  • 2015-01-03 22:13:09
  • 3680

Leetcode 173 Binary Search Tree Iterator 二叉查找树迭代器

实现一个适用于二叉查找树的迭代器,该迭代器通过二叉查找树的根结点来实例化。调用next()返回二叉查找树中的最小的元素。next()和hasNext()运行的平均时间复杂度为O(1),空间复杂度为O(...
  • smile_watermelon
  • smile_watermelon
  • 2015-08-04 18:27:43
  • 1691

[C++]LeetCode: 93 Binary Search Tree Iterator (经典题,非递归的中序遍历)

题目: Implement an iterator over a binary search tree (BST). Your iterator will be initialized with...
  • cinderella_niu
  • cinderella_niu
  • 2015-01-14 16:32:34
  • 1329

[Java]leetcode173 Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro...
  • fumier
  • fumier
  • 2015-04-10 08:52:17
  • 665

LeetCode(173) Binary Search Tree Iterator解题报告

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro...
  • Ssunsets
  • Ssunsets
  • 2015-12-15 22:43:38
  • 237

Binary Search Tree Iterator leetcode

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro...
  • shiralwz
  • shiralwz
  • 2016-08-17 23:06:55
  • 152

Convert Sorted List to Binary Search Tree -- LeetCode

原题链接: http://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/  这个题是二分查找树的题目,要把一个有...
  • linhuanmars
  • linhuanmars
  • 2014-04-17 07:57:02
  • 16631

【LeetCode】669 Trim a Binary Search Tree

原题地址:669. Trim a Binary Search Tree。题意给定一棵二叉搜索树和最小最大边界L和R,修剪这棵树,使得其中的元素位于L和R之间。解法 当root的值位于L和R之间,则递归...
  • hlljjy123
  • hlljjy123
  • 2017-09-08 15:53:21
  • 1619
收藏助手
不良信息举报
您举报文章:LeetCode Binary Search Tree Iterator
举报原因:
原因补充:

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