码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_173_Binary Search Tree Iterator

时间:2015-04-03 17:34:15      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:二叉查找树   遍历序列   

描述:

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

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

思路:

这道题想了好久,知道用中序遍历来解决,用一个list将遍历的元素存储起来一下就解决了,但是空间复杂度不行。具体怎么解决,如何控制程序的终止困扰了我好久。知道我想起来至多用O(h) memory,我想到了直接把一趟遍历后返回开始之前的所有元素存储起来不就正好符合题目要求了么,bravo!

代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class BSTIterator {

	List<Integer> list = new ArrayList<Integer>();// 存放结点的值
	Stack<TreeNode> st = new Stack<TreeNode>();// 遍历的过程中存放结点

	public BSTIterator(TreeNode root) {
		if (root != null)
			st.push(root);
	}

	/** @return whether we have a next smallest number */
	public boolean hasNext() {
		boolean flag1 = list.isEmpty(), flag2 = st.isEmpty();
		if (!flag1)
			return true;
		if (flag1 && !flag2)
			return iteratorDemo();
		return false;
	}

	/** @return the next smallest number */
	public int next() {
		int num = list.get(0);
		list.remove(0);
		return num;
	}
//中序遍历
	public boolean iteratorDemo() {
		TreeNode top = null;
		while (!st.empty()) {
			top = st.peek();
			while (top.left != null) {
				st.push(top.left);
				top = top.left;
			}
			while (top.right == null) {
				list.add(top.val);
				st.pop();
				if (!st.empty())
					top = st.peek();
				else
					break;
			}
			if (!st.empty()) {
				list.add(top.val);
				st.pop();
				st.push(top.right);
				break;
			}
		}
		if(list.isEmpty())
			return false;
		return true;
	}
}


/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */


结果:

技术分享

leetcode_173_Binary Search Tree Iterator

标签:二叉查找树   遍历序列   

原文地址:http://blog.csdn.net/mnmlist/article/details/44855551

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!