package com.code.binarytree;
import java.util.Stack;
/**
* 二叉树的后序遍历
*/
public class AfterOrder {
/**
* 二叉树的递归后序遍历
* @param binaryTree 二叉树
*/
public static void afterOrder(BinaryTree binaryTree){
if(binaryTree != null){
afterOrder(binaryTree.left);
afterOrder(binaryTree.right);
System.out.println(binaryTree.value);
}
}
/**
* 二叉树的非递归后序遍历使用双栈方法
* @param binaryTree 二叉树
*/
public static void afterOrder02(BinaryTree binaryTree){
Stack<BinaryTree> stack1 = new Stack<>();
Stack<BinaryTree> stack2 = new Stack<>();
BinaryTree node = binaryTree;
if(node != null){
stack1.push(node);
}
while(!stack1.isEmpty()){
BinaryTree treeNode = stack1.pop();
stack2.push(treeNode);
if(treeNode.left != null){
stack1.push(treeNode.left);
}
if(treeNode.right != null){
stack1.push(treeNode.right);
}
}
while(!stack2.isEmpty()){
System.out.println(stack2.pop().value);
}
}
/**
* 二叉树的后序遍历非递归方法,单栈法
* @param binaryTree 二叉树
*/
public static void afterOrder03(BinaryTree binaryTree){
Stack<BinaryTree> stack = new Stack<>();
BinaryTree node = binaryTree;
if(node != null){
stack.push(node);
}
//记录上一次访问的节点
BinaryTree last = null;
while(!stack.isEmpty()){
node = stack.peek();
//判断当前节点是否是叶子节点或者是已经遍历完右节点,或者右节点不存在已经遍历完左节点,输出节点值然后出栈,记录下出栈的值
if((node.right == null && node.left == null) || (node.right == null && node.left == last)|| node.right == last){
System.out.println(node.value);
last = stack.pop();
}else {
//按照右节点左节点的顺序入栈
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
}
}
public static void main(String[] args){
//新建二叉树
BinaryTree root = new BinaryTree(1);
BinaryTree left = new BinaryTree(2);
BinaryTree right = new BinaryTree(3);
BinaryTree left02 = new BinaryTree(4);
BinaryTree right02 = new BinaryTree(5);
BinaryTree right03 = new BinaryTree(6);
left.right = right02;
left.left = left02;
root.left = left;
root.right = right;
right02.left = right03;
//递归后序遍历
afterOrder(root);
System.out.println("----------------");
afterOrder02(root);
System.out.println("----------------");
afterOrder03(root);
}
//结果465231
}