二叉樹的遞歸遍歷和非遞歸遍歷


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);
        }
    }
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM