二叉树前序、中序、后序遍历,和直观打印。

2018-05-27  本文已影响7人  HWilliamgo
//前序遍历
public static void preOrderedPrint(TreeNode root){
    if (root!=null){
        System.out.print(root.value);
        preOrderedPrint(root.leftNode);//删去了多余的if(root.leftNode!=null)的条件判断。
        preOrderedPrint(root.rightNode);
    }
}
//中序遍历
public static void inOrderedPrint(TreeNode root){
    if (root!=null){
        inOrderedPrint(root.leftNode);
        System.out.print(root.value);
        inOrderedPrint(root.rightNode);
    }
}
//后序遍历
public static void postOrderedPrint(TreeNode root){
    if (root!=null){
        postOrderedPrint(root.leftNode);
        postOrderedPrint(root.rightNode);
        System.out.print(root.value);
    }
}

用如下的完全二叉树结构来做试验:


TreeNode newOne=createTree(root,list);
preOrderedPrint(newOne);

打印:0137849256
很不直观有木有,于是写一个较为直观的方法:

public static void vividPreOrderedPrint(TreeNode root,int depth) {
    if (root != null) {
        System.out.println();//换行
        for (int i=0;i<depth;i++){//for循环来打印value前的空格
            System.out.print("-");//结点深度越大,空格越多
        }
        System.out.print(root.value);
        depth++;
        vividPreOrderedPrint(root.leftNode,depth);
        vividPreOrderedPrint(root.rightNode,depth);
    }
}
TreeNode newOne=createTree(root,list); 
vividPreOrderedPrint(newOne,0);

打印:
0
-1
--3
---7
---8
--4
---9
-2
--5
--6
这就很清楚了,0是根节点,有一个“-”的是深度为1的结点,分别是1和2,有两个“-”的是深度为2的结点,分别是......

上一篇 下一篇

猜你喜欢

热点阅读