二叉树前序中序后序层序遍历问题

定义二叉树 

/**
 * 定义二叉树
 */
public class BinaryTree {
    private int data;
    private BinaryTree left;
    private BinaryTree right;
}

给二叉树添加元素
BinaryTree f = new BinaryTree(6, null, null);
BinaryTree e = new BinaryTree(5, null, null);
BinaryTree d = new BinaryTree(4, null, null);
BinaryTree c = new BinaryTree(3, f, null);
BinaryTree b = new BinaryTree(2, d, e);
BinaryTree a = new BinaryTree(1, b, c);
 

前序遍历:  

   
/** * 前序递归遍历 */ public static void recursion(BinaryTree node){ System.out.println(node.getData());   if (node.getLeft()!=null){ recursion(node.getLeft()); } if (node.getRight()!=null){ recursion(node.getRight()); } }

/**
* 前序非递归遍历
  1、先将根节点压入栈中,输出 val,再将右边节点、左节点压入栈中
  2、左节点输出 val 再将左节点的右节点,左节点,压入栈中,直道将左节点的 val值全部输出
  3、再将右节点 val 输出,再将节点的右节点的val 值全部输出
* @param node
*/
public static void noRecursion(BinaryTree node){
Stack<BinaryTree> sta = new Stack<>();
if(node!=null){//先把第一个 二叉树压入栈中
sta.push(node);
}
while (!sta.empty()){
BinaryTree nodes=sta.pop(); //在栈定取出 二叉树
System.out.println(nodes.getData()+" ");
if(nodes.getRight()!=null){
sta.push(nodes.getRight()); //先把右边树 压入栈中
}
if(nodes.getLeft()!=null){
sta.push(nodes.getLeft()); //再把左边树 压入栈中
}
}
}

  

 中序遍历:  可以将中序遍历看成 压扁的二叉树(4、2、5、1、6、3)

    /**
     * 中序递归遍历
     */
    public static void zhong(BinaryTree node){
        if(node.getLeft()!=null){
            zhong(node.getLeft());
        }
        System.out.print(node.getData()+" ");
        if(node.getRight()!=null){
            zhong(node.getRight());
        }
    }
/**
* 中序非递归遍历
* * 中序遍历,非递归实现
* 1,首先从根节点出发一路向左,入栈所有的左节点;
* 2,出栈一个节点,输出该节点val值,查询该节点是否存在右节点,
* 若存在则从该右节点出发一路向左入栈该右节点所在子树所有的左节点;
* 3,若不存在右节点,则出栈下一个节点,输出节点val值,同步骤2操作;
* 4,直到节点为null,且栈为空。
*/
public static void inorderTraversal(BinaryTree node){
Stack<BinaryTree> stack = new Stack<>();
while (node!=null||!stack.empty()){
while (node!=null){
stack.push(node);
node=node.getLeft();
}
if(!stack.empty()){
BinaryTree pop = stack.pop();
System.out.println(pop.getData()+" ");
node=node.getRight();
}
}
}


原文地址:https://www.cnblogs.com/axu521/p/10492658.html