Untitled
unknown
java
a year ago
2.5 kB
6
Indexable
Never
public static <T> void preOrderVisitWRec(BinaryTree.TreeNode<T> treeNode, Visitor<T> visitor) { if (treeNode == null) { return; } int level = 0; Stack<BinaryTree.TreeNode<T>> stack = new Stack<>(); stack.push(treeNode); while (!stack.isEmpty()) { BinaryTree.TreeNode<T> rightBro; treeNode = stack.pop(); visitor.visit(treeNode.getValue(), level); if (treeNode.getRight() != null) { stack.push(treeNode.getRight()); } rightBro = treeNode.getRight(); if (treeNode.getLeft() != null) { stack.push(treeNode.getLeft()); level++; } treeNode = treeNode.getLeft(); if (rightBro == null && treeNode == null) { level--; } } } public static <T> void inOrderVisitWRec(BinaryTree.TreeNode<T> treeNode, Visitor<T> visitor) { Stack<BinaryTree.TreeNode<T>> stack = new Stack<>(); int level = 0; if (treeNode != null) { stack.push(treeNode); treeNode = treeNode.getLeft(); } while (treeNode != null || !stack.isEmpty()) { while (treeNode != null) { stack.push(treeNode); level++; treeNode = treeNode.getLeft(); } treeNode = stack.pop(); visitor.visit(treeNode.getValue(), level); level--; treeNode = treeNode.getRight(); if (treeNode != null ) { level++; } } } public static <T> void postOrderVisitWRec(BinaryTree.TreeNode<T> treeNode, Visitor<T> visitor) { Stack<BinaryTree.TreeNode<T>> stack = new Stack<>(); BinaryTree.TreeNode<T> lastVisitedNode = null; while (!stack.isEmpty() || treeNode != null) { if (treeNode != null) { stack.push(treeNode); treeNode = treeNode.getLeft(); } else { BinaryTree.TreeNode<T> peekNode = stack.peek(); if (peekNode.getRight() != null && lastVisitedNode != peekNode.getRight()) { treeNode = peekNode.getRight(); } else { visitor.visit(peekNode.getValue(), 0); lastVisitedNode = stack.pop(); } } } }