树的后序遍历:左右根,代码写起来还是很简单的,就几行代码。
public void postOrder(Node node) {
if(node.getLeft() != null){
postOrder(node.getLeft());
}
if(node.getRight != null){
postOrder(node.getRight());
}
System.out.print(node.getValue());
}
这里如果不是很熟悉,可以自己debug下,在纸上自己画画过程,当初我学汉诺塔的时候也很懵逼的,在纸上画了几次调用过程后,心里才有点清晰的感觉。
树的后序非层次遍历:其实是用了栈的特性,由于我们遍历的时候不知到是从左边来的,还是右边来的,所以我们需要在给每一个元素加一个对应的标志位。我们可以用一个栈来存储元素,一个栈用来标记是否从右边遍历完上来的。
public void postOrder(Node treeNode) {
Node node = treeNode;
Stack<Node> stack = new Stack();
Stack<Integer> stack1 = new Stack();
while(node.getLeft() != null) {
stack.push(node);
stack1.push(1);
node = node.getLeft();
}
while(stack.size() > 0 || node != null) {
if (node == null) {
if (stack1.peek() == 1) {
node = stack.peek().right;
Integer element = stack1.pop();
stack1.push(0);
} else {
node = stack.pop();
stack1.pop();
System.out.println(node.getValue());
node = null;
}
} else {
stack.push(node);
stack1.push(1);
node = node.left;
}
}
}