后序遍历递归定义: 先左子树,后右子树,再根节点。
后序遍历的难点在于:需要判断上次访问的节点是位于左子树,还是右子树。
若是位于左子树,则需跳过根节点,先进入右子树,再回头访问根节点;
若是位于右子树,则直接访问根节点。直接看代码,代码中有详细的注释。
public void behindOrder(Tree n){
if(n!= null){
behindOrder(n.left_child);
behindOrder(n.right_child);
System.out.print(n.val+" ");
}
}
/**
* public class Node {
public int data; //树结点标号
public Node lchild; //左子树
public Node rchild; //右子树
}
后序遍历递归定义:先左子树,后右子树,再根节点。
后序遍历的难点在于:需要判断上次访问的节点是位于左子树,还是右子树。
若是位于左子树,则需跳过根节点,先进入右子树,再回头访问根节点;
若是位于右子树,则直接访问根节点。
*/
public void behindOrder2(Tree node){
if(node==null)
return;
Stack<Tree> s = new Stack<Tree>();
Tree curNode; //当前访问的结点
Tree lastVisitNode; //上次访问的结点
curNode = node;
lastVisitNode = node;
//把currentNode移到左子树的最下边
while(curNode!=null){
s.push(curNode);
curNode = curNode.left_child;
}
while(!s.empty()){
curNode = s.pop(); //弹出栈顶元素
//一个根节点被访问的前提是:无右子树或右子树已被访问过
if(curNode.right_child !=null && curNode.right_child != lastVisitNode){
//根节点再次入栈
s.push(curNode);
//进入右子树,且可肯定右子树一定不为空
curNode = curNode.right_child;
while(curNode!=null){
//再走到右子树的最左边
s.push(curNode);
curNode = curNode.left_child;
}
}else{
//访问
System.out.print(curNode.val+" " );
//修改最近被访问的节点
lastVisitNode = curNode;
}
} //while
}