二叉树遍历——先序遍历、中序遍历、后序遍历(递归+非递归)

二叉树遍历算法

其中我把递归遍历算法注释掉了,因为比较容易理解。
二叉树遍历——先序遍历、中序遍历、后序遍历(递归+非递归)_第1张图片

public class TreeTest {

    public static void main(String[] args) {
        Tree tree = initTree();
//        DLR(tree);
//        System.out.println("=====");
//        LDR(tree);
//        System.out.println("=====");
        LRD(tree);
    }

    //根 -》左-》右
    public static void DLR(Tree tree) {
        //递归
//        if (tree != null) {
//            System.out.println(tree.value);
//            DLR(tree.left);
//            DLR(tree.right);
//        }

        //非递归算法
        Stack<Tree> stack = new Stack<>();
        stack.add(tree);
        while (!stack.isEmpty()) {
            Tree pop = stack.pop();
            System.out.println(pop.value);
            if (pop.right != null) {
                stack.push(pop.right);
            }
            if (pop.left != null) {
                stack.push(pop.left);
            }
        }
    }


    //左-》根 -》右
    public static void LDR(Tree tree) {
//        if (tree != null) {
//            LDR(tree.left);
//            System.out.println(tree.value);
//            LDR(tree.right);
//        }
        //非递归算法
        Stack<Tree> stack = new Stack<>();
        Tree cur = tree;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            if (!stack.isEmpty()) {
                Tree pop = stack.pop();
                System.out.println(pop.value);
                cur = pop.right;
            }

        }

    }

    //左-》右-》根
    public static void LRD(Tree tree) {
//        if (tree != null) {
//            LRD(tree.left);
//            LRD(tree.right);
//            System.out.println(tree.value);
//        }
        Stack<Tree> stack = new Stack<>();
        Stack<Tree> stack2 = new Stack<>();
        stack.push(tree);
        while (!stack.isEmpty()){
            Tree pop = stack.pop();
            stack2.push(pop);
            if (pop.left!= null){
                stack.push(pop.left);
            }
            if(pop.right != null){
                stack.push(pop.right);
            }
        }
        while (!stack2.isEmpty()){
            System.out.println(stack2.pop().value);
        }


    }

    public static Tree initTree() {
        Tree tree3 = new Tree(null, null, 3);
        Tree tree7 = new Tree(tree3, null, 7);
        Tree tree17 = new Tree(null, null, 17);
        Tree tree20 = new Tree(null, null, 20);
        Tree tree18 = new Tree(tree17, tree20, 18);
        Tree tree15 = new Tree(tree7, tree18, 15);
        return tree15;

    }
  static class Tree {
        Tree left;
        Tree right;
        Integer value;

        public Tree(Tree left, Tree right, Integer value) {
            this.left = left;
            this.right = right;
            this.value = value;
        }
    }
}

你可能感兴趣的:(算法)