不会写,本质上是忘了in order traversal怎么写了。然而preorder, inorder, postorder的iterative traversal是要背下来的。
Binary Tree Inorder Traversal Iterative way
必须要知道是用stack这个数据结构完成。关于怎么记,其实就是想一下几个过程在脑子里:
- “一路向左” inorder先左边,放BST里就是最小的,所以inorder出来的结果如果是BST就是递增的。一直从
curt = root
一直curt = curt.left
走到左边尽头,边走边压到栈里头 - 找下一个最小的节点,我们知道应该在最左边节点的右边的最左边开始找。如果
poll()
出来当前的节点没有右子树,说明找不到比该节点的父节点更小的节点了,那我们就继续poll出栈。如果有右子树,我们就找右子树的最小值也就是最左边的节点,继续“一路向左”,循环条件是!stack.isEmpty()
这整个搜索过程我们要记录一路向左遇到的所有节点,所以要选择stack来存储。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null){
return res;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode curt = root;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
while (!stack.isEmpty()){
TreeNode smallest = stack.pop();
res.add(smallest.val);
curt = smallest.right;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
}
return res;
}
}
本题其实就是把traversal分配到了两部分,一部分是在constructor里面,一部分是next() method. hasNext()很明显是O(1), next()在是amortized O(1). 为什么呢?比如我们call next()直到我们traverse整棵树,那么总时间是O(N), 因为没个节点都被访问了,然后一共call了n次,所以平均下来一次是O(1).
空间复杂度是O(h)因为每个level存一个, 一共树高个节点存了。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stack;
//inorder traversal
public BSTIterator(TreeNode root) {
stack = new Stack<>();
TreeNode curt = root;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pop();
TreeNode curt = node.right;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
return node.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/