二叉树的遍历

递归方式调用:

public class Solution {
    public static void main(String[] args) {
        TreeNode[] node = new TreeNode[10];
        for (int i = 0; i < 10; i++) {
            node[i] = new TreeNode(i);
        }
        for (int i = 0; i < 10; i++) {
            if (i * 2 + 1 < 10) {
                node[i].left = node[i * 2 + 1];
            }
            if (i * 2 + 2 < 10) {
                node[i].right = node[i * 2 + 2];
            }
        }
        System.out.println("二叉树的前序遍历");
        preOrderRe(node[0]);
        System.out.println();

        System.out.println("二叉树的中序遍历");
        midOrderRe(node[0]);
        System.out.println();

        System.out.println("二叉树的后续遍历");
        postOrderRe(node[0]);
    }

    /**
     * 前序遍历
     *
     * @param biTree
     */
    public static void preOrderRe(TreeNode biTree) {
        // 递归实现
        System.out.print(biTree.value + "\t");
        TreeNode leftTree = biTree.left;
        if (leftTree != null) {
            preOrderRe(leftTree);
        }
        TreeNode rightTree = biTree.right;
        if (rightTree != null) {
            preOrderRe(rightTree);
        }
    }

    /**
     * 中序遍历
     *
     * @param biTree
     */
    public static void midOrderRe(TreeNode biTree) {
        if (biTree == null) {
            return;
        } else {
            midOrderRe(biTree.left);
            System.out.print(biTree.value + "\t");
            midOrderRe(biTree.right);
        }

    }

    /**
     * 后续遍历
     *
     * @param biTree
     */
    public static void postOrderRe(TreeNode biTree) {
        if (biTree == null) {
            return;
        } else {
            postOrderRe(biTree.left);
            postOrderRe(biTree.right);
            System.out.print(biTree.value + "\t");
        }
    }

    static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode(int value) {
            this.value = value;
        }
    }
}

  运行结果:

 

posted @ 2020-10-28 15:04  looyee  阅读(70)  评论(0编辑  收藏  举报