https://oj.leetcode.com/problems/binary-search-tree-iterator/
Topic
Give the one or two-fork tree root to implement a iterator traversal, the iterator with two functions.
Boolen Hasnext () returns whether the tree also has the next inorder traversal node.
TreeNode next (), each call returns the next Inorder traversal node.
Class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode (int x) {
val = x;
}
}
Analysis
#1 easiest way to do this is to iterate through the binary tree and put it in the list. is the extra space required O (N), the disadvantage is that the initialization time is longer, the advantage is that each next is the complexity of O (1)
#2 the following non recursive sequence traversal into Hasnext and next. The worst need O (n) extra space, the advantage is to initialize O (1), the disadvantage is that the worst next complexity is O (n). Space is O (H).
public class Solution {public
list<integer> inordertraversal (TreeNode root) {
list<integer> result = new arraylist<integer> ();
stack<treenode> stack = new stack<treenode> ();
TreeNode cur = root;
The stack was empty at the beginning but cur point to root while
(cur!= null | |!stack.empty ()) {
//left to the end while
(cur!= null) {
Stack.push (cur);
cur = cur.left;
}
Cur is empty, pop
cur = stack.pop ();
Result.add (cur.val);
Turn right
cur = cur.right;
} The ' a ' return result
}
}
Implement
public class solution{
private TreeNode cur;
Private stack<treenode> Stack = new stack<treenode> ();
Public Solution (TreeNode root) {
cur = root;
}
public Boolean Hasnext () {return
(cur!= null | |!stack.empty ());
}
Public TreeNode Next () {while
(cur!= null) {
stack.push (cur);
cur = cur.left;
}
TreeNode result = Stack.pop ();
cur = result.right;
return result;
}