LeetCode(173) Binary Search Tree Iterator解题报告
2015-12-15 22:43
316 查看
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.
解题思路:
下面有两种解法,都可以ac,第一种是直接遍历所有的树节点,然后压入栈中,第二种是不压入所有的树节点,一个出栈,才会将该节点右子树的根节点及往下的所有左子节点压入栈,不需要遍历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.
解题思路:
下面有两种解法,都可以ac,第一种是直接遍历所有的树节点,然后压入栈中,第二种是不压入所有的树节点,一个出栈,才会将该节点右子树的根节点及往下的所有左子节点压入栈,不需要遍历BST
public class BSTIterator { Stack<Integer> result; public BSTIterator(TreeNode root) { result = deal(root); } public Stack<Integer> deal(TreeNode root){ Stack<Integer> res = new Stack<Integer>(); if(root == null) return res; res.addAll(deal(root.right)); res.push(root.val); res.addAll(deal(root.left)); return res; } /** @return whether we have a next smallest number */ public boolean hasNext() { return result.size() != 0 ? true : false; } /** @return the next smallest number */ public int next() { return result.pop(); } }
public class BSTIterator { Stack<TreeNode> result; public BSTIterator(TreeNode root) { result = new Stack<TreeNode>(); TreeNode temp = root; while(temp != null){ result.push(temp); temp = temp.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return result.size() != 0 ? true : false; } /** @return the next smallest number */ public int next() { TreeNode t = result.pop(); TreeNode temp; if(t.right != null){ result.push(t.right); temp = result.peek(); while(temp.left != null){ result.push(temp.left); temp = temp.left; } } return t.val; } }
相关文章推荐
- JNI 调用第三方dll 报错 RUNTIME ERROR R6031
- Space Ant
- Java多线程和并发编程实践学习总结---提高篇1
- threadpool——python线程池
- 碰撞运动
- Android初识-adb启动失败原因
- Trees Made to Order
- android系统颜色color资源问题分析
- PHP获取今天内的时间 今天开始和结束的时间戳
- Bug of VS2015+WDK
- [Coursera]算法基础_Week9_考试_Q3
- HDU 2089 & HDU 3555 数位dp
- js数组对象
- Tomcat去除项目名称和端口号,直接使用ip地址访问项目的方法
- Android PullToRefresh 详解
- C /C++标准库 - <cstdlib>(stdlib.h)
- 月入30K的程序员要避开哪些坑?
- 自己用的一个ASP.Net MVC分页拿出来分享下(转)
- Solr 5.x集成中文分词word,mmseg4j
- Office application 版本