树的前中后序遍历(递归与非递归版)

树的前中后序遍历(递归与非递归版)

对于二叉树而言,我们首先应当知晓的知识就是二叉树的遍历。

首先,二叉树遍历有前中后三种遍历方法,在递归版中,前序遍历就是第一次遇到该节点就打印,中序遍历就是第二次遇到打印该节点,后续遍历就是第三次遇到该节点打印。

递归实质是系统帮助我们压栈,保存现场信息,而非递归就需要我们自己来压栈。

二叉树结构:


    public static class Node{
        public int value;
        public Node right = null;
        public Node left = null;
        public Node(int data){
            this.value = data;
        }
    }

递归版前序遍历:


    public static void preOrderRecur(Node head){
        if(head == null ){
            return;
        }
        System.out.print(head.value + " ");
        preOrderRecur(head.left);
        preOrderRecur(head.right);

递归版中序遍历:


    public static void inOrderRecur(Node head){
        if(head == null){
            return;
        }
        inOrderRecur(head.left);
        System.out.print(head.value + " ");
        inOrderRecur(head.right);
    }

递归版后序遍历:


    public static void posOrderRecur(Node head){
        if(head == null){
            return;
        }
        posOrderRecur(head.left);
        posOrderRecur(head.right);
        System.out.print(head.value+ " ");
    }

非递归版前序遍历:


public static void preOrderUnRecur(Node head){
        if(head == null){
            return;
        }
            Stack<Node> stack = new Stack<Node>();
            stack.add(head);
            while (!stack.isEmpty()) {
                head = stack.pop();
                System.out.print(head.value+" ");
                if (head.right != null) {
                    stack.push(head.right);
                }
                if (head.left != null) {
                    stack.push(head.left);
                }
            }
            System.out.println();
    }

非递归版中序遍历:


 public static void inOrderUnRecur(Node head){
        if(head == null){
            return;
        }
        Stack<Node> stack = new Stack<Node>();
        while (!stack.isEmpty() || head != null){
            if(head != null){
                stack.push(head);
                head = head.left;
            }else {
                head = stack.pop();
                System.out.print(head.value+" ");
                head = head.right;
            }
        }
        System.out.println();
    }

非递归版后序遍历:


 public static void posOrderUnRecur(Node head){
        if(head == null){
            return;
        }
        if(head != null) {
            Stack<Node> stack = new Stack<Node>();
            Stack<Node> stack1 = new Stack<Node>();
            stack.push(head);
            while (!stack.isEmpty()) {
                head = stack.pop();
                stack1.push(head);
                if (head.left != null) {
                    stack.push(head.left);
                }
                if (head.right != null) {
                    stack.push(head.right);
                }
            }
            while (!stack1.isEmpty()) {
                System.out.print(stack1.pop().value + " ");
            }
        }
    }

main函数


猜你喜欢

转载自blog.csdn.net/qq_38180223/article/details/81007114