后續遍歷要保證根結點在左孩子和右孩子訪問之后才能訪問,因此對於任一結點P,先將其入棧。如果P不存在左孩子和右孩子,則可以直接訪問它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被訪問過了,則同樣可以直接訪問該結點。若非上述兩種情況,則將P的右孩子和左孩子依次入棧,這樣就保證了每次取棧頂元素的時候,左孩子在右孩子前面被訪問,左孩子和右孩子都在根結點前面被訪問。
private static void postOrderNonRecursiveEasily(Node root) {
System.out.println("postOrderNonRecursiveEasiliy :");
Assert.notNull(root, "root is null");
Node lastVisitNode = null;
Stack <Node> stack = new Stack <Node>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.peek();
//如果P不存在左孩子和右孩子
//或者存在左孩子或者右孩子,但是其左孩子和右孩子都已被訪問過了
if ((root.getLeftNode() == null && root.getRightNode() == null) || (
lastVisitNode != null && (lastVisitNode == root.getLeftNode()
|| lastVisitNode == root.getRightNode()))) {
System.out.println(root.getValue());
lastVisitNode = root;
stack.pop();
} else {
if (root.getRightNode() != null) {
stack.push(root.getRightNode());
}
if (root.getLeftNode() != null) {
stack.push(root.getLeftNode());
}
}
}
}