原题链接:173. Binary Search Tree Iterator
Sequential traversal non-recursive implementation in "Thought-java"
We know the binary search tree the current node value is always greater than any node value on the left subtree, and is always greater than any node value on the right subtree. To remove the node from small to large, we can use the binary tree in the sequence traversal, this idea to borrow a stack to achieve, if the two-tree in the middle of the sequence traversal idea is not very clear, you can refer to my another blog: Leetcode 94. Binary tree inorder traversal-sequence Traversal | recursive | non-recursive
public class Bstiterator {
stack<treenode> Stack = new stack<treenode> ();
Public bstiterator (TreeNode root) {while
(root!= null) {
stack.add (root);
root = Root.left;
}
}
/** @return Whether we have a next smallest number */Public
Boolean Hasnext () {return
!stack.isempty ();
}
/** @return The next smallest number */public
int Next () {
TreeNode temp = Stack.pop ();
int val = temp.val;
if (temp.right!= null) {
temp = temp.right;
while (temp!= null) {
Stack.add (temp);
temp = Temp.left;
}
}
return val;
}
}
61/61 Test cases passed. Runtime:6 ms Your Runtime beats 78.97% of javasubmissions.
"Thinking 2-java"
If we break the routine and do it without the stack, we need to transform the strategy and apply a few pointers:
The idea is to use pointers to add the leftmost point to the right of the root pointer.
public class Bstiterator {
TreeNode root = new TreeNode (0);
Public bstiterator (TreeNode root) {
this.root.right = root;
}
/** @return Whether we have a next smallest number *
/public boolean hasnext () {return
root.right!= null;
}
/** @return The next smallest number *
/public int next () {
TreeNode next = root.right;
if (Next.left = = null) {
root = next;
return next.val;
}
TreeNode right = Root.right;
TreeNode parent = root;
while (Next.left!= null) {
parent = next;
Next = Next.left;
}
Parent.left = next.right;
Root.right = Next;
Next.right = right;
root = Root.right;
Return Root.val
}
}
61/61 Test cases passed. Runtime:5 ms Your Runtime beats 94.32% of javasubmissions.