二叉树的递归遍历和非递归遍历

node 节点定义

    public static class Node{
        public int val;
        public Node left;
        public Node right;
        
        public Node(int val){
            this.val = val;
        }
    }
    

 

递归前序遍历:

public static void preOrder(Node head){
        if (head != null ) {
            System.out.print(head.val);
            preOrder(head.left);
            preOrder(head.right);
        }
    }

 

非递归前序遍历:先遍历当前节点,再遍历他的左子树,再到右子树。每个节点都保存着左右子树的信息。

因为当前节点被弹出,所以必须要先保存他的右子树。如果不将右子树不压栈的话,将会丢失信息。

public static void preOrder01(Node head) {
        
        if (head == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        stack.push(head);
        
        while(!stack.isEmpty()){
            
            Node cur = stack.pop();
            System.out.println(cur.val);
            
            if( cur.right != null ){
                stack.push(cur.right);
            }
            if (cur.left != null ) {
                stack.push(cur.left);
            }
        }
        
    }

 

中序递归遍历:

public static void midOrder(Node head){
        if (head != null) {
            preOrder(head.left);
            System.out.print(head.val);
            preOrder(head.right);
        }
    }

 

中序非递归遍历: 一直将他的左子树压栈。 一直到左子树最左的节点。  

public static void midOder01(Node head){
        if (head == null){
            return ;
        }
        
        Stack<Node> stack = new Stack<>();
        stack.push(head);
        
        while(!stack.empty() || head != null){
            if( head.left != null ){
                stack.push(head.left);
            }else {
                head = stack.pop();
                System.out.println(head.val);
                if (head.right != null) {
                    stack.push(head.right);
                }
            }
        }
    }

 

后序递归遍历:

public static void laterOrder(Node head){
        if (head != null) {
            laterOrder(head.left);
            laterOrder(head.right);
            System.out.println(head.val);
        }
    }

 

后序非递归遍历:

维护两个栈,第一个栈遍历树的顺序是 中右左

第二个  左右中。

public static void laterOrder1(Node head) {
        
        if (head == null) {
            return ;
        }
        Stack<Node> s1 = new Stack<>();
        Stack<Node> s2 = new Stack<>();
        
        s1.push(head);
        while(!s1.empty()){
            
            head = s1.pop();
            s2.push(head);
            if (head.right != null) {
                s1.push(head.left);
            }
            if (head.left != null) {
                s1.push(head.right);
            }
            
        }
        while(!s2.empty()){
            head = s2.pop();
            System.out.println(head.val);
        }
    }
    

 

posted @ 2018-12-23 09:26  清湾大威少  阅读(2448)  评论(0编辑  收藏  举报