BAEL-4864: Fix traverseInOrderWithoutRecursion method (#10588)

Co-authored-by: Krzysztof Woyke <krzysztof.woyke.sp@lhsystems.com>
This commit is contained in:
kwoyke
2021-03-24 22:09:02 +01:00
committed by GitHub
parent 9a580ea9fc
commit 23503a0673
2 changed files with 53 additions and 30 deletions
@@ -148,48 +148,46 @@ public class BinaryTree {
}
}
public void traverseInOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack = new Stack<>();
Node current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
Node top = stack.pop();
visit(top.value);
current = top.right;
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
while(current.left != null) {
current = current.left;
stack.push(current);
}
while (current != null && !stack.isEmpty()) {
current = stack.pop();
visit(current.value);
if(current.right != null) {
current = current.right;
stack.push(current);
}
if (current.right != null)
stack.push(current.right);
if (current.left != null)
stack.push(current.left);
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
current = stack.pop();
visit(current.value);
if(current.right != null)
stack.push(current.right);
if(current.left != null)
stack.push(current.left);
}
}
public void traversePostOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack = new Stack<>();
Node prev = root;
Node current = root;
stack.push(root);
while (!stack.isEmpty()) {
while (current != null && !stack.isEmpty()) {
current = stack.peek();
boolean hasChild = (current.left != null || current.right != null);
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));