[二叉樹專題]求二叉樹的前中後遍歷(遞歸,迭代)

/* 前序遞歸遍歷
1. 若是二叉樹爲null,則直接返回
2. 若是二叉樹不爲null,先訪問根節點再訪問左子樹,最後訪問右子樹
*/
public static void preorderTraversalRec(TreeNode root){
    if(root == null){
        return ;
    }
    System.out.print(root.val + " ");
    preorderTraversalRec(root.left);
    preorderTraversalRec(root.right);
}
/*前序迭代遍歷
用一個輔助stack,老是把右孩子放進棧。
*/
public static void preorderTraversal(TreeNode root){
    if(root == null)
        return null;
    
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);
    
    while(!stack.isEmpty()){
        TreeNode cur= stack.pop();
        System.out.print(cur.val + " ");
        
        //關鍵點:先壓入右孩子,再壓入左孩子,這樣在出棧的時會先打印左孩子,再打印右孩子。
        if(cur.right != null){
            stack.push(cur.right);
        }
        if(cur.left != null){
            stack.push(cur.left);
        }
    }  
}

/*中序遞歸遍歷
1。若是二叉樹爲null,則直接返回
2. 若是二叉樹不爲null,則先訪問左子樹,再訪問根節點,最後訪問右子樹。
*/
public static void inorderTravelsalRec(TreeNode root){
    if(root == null){
        return ;
    }
    
    inorderTravelsalRec(root.left);
    System.out.print(root.val + " ");
    inorderTravelsalRec(root.right);
}
/*中序迭代遍歷
用棧先把根節點的全部左孩子都添加到棧內,而後輸出棧頂元素,再處理棧頂元素的右子樹
*/
publiv static void inorderTravelsal(TreeNode root){
    if(root == null){
        return ;
    }
    stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode cur = root;
    while(true){
        while(cur != null){ //先添加全部的左孩子到棧內
            stack.push(cur);
            cur = cur.left;
         }
         if(stack.isEmpty()){
             break;
         }
         
         //由於此時已經沒有左孩子,因此輸出棧頂元素
         cur = stack.pop();
         System.out.print(cur.val + " ");
         cur = cur.right;
    }
}
/*後序遞歸遍歷
1.若是二叉樹爲null,則直接返回;
2.若是二叉樹不爲null,先訪問左子樹,再訪問右子樹,最後訪問根節點
*/
public static void postorderTravelsalRec(TreeNode root){
    if(root == null){
        return ;
    }
    
    postorderTravelsalRec(root.left);
    postorderTravelsalRec(root.right);
    System.out.print(root.val + " ");
}
/*後序迭代遍歷
*/
public static void postorderTravelRec(TreeNode root){
    if(root == null){
        return ;
    }
    
    Stack<TreeNode> s = new Stack<TreeNode>();//第一個stack用於添加node和他的左右孩子
    Stack<TreeNode> output = new Stack<TreeNode>();//第二個stack用於翻轉第一個stack輸出
    
    s.push(root);
    while(!s.isEmpty()){
        TreeNode cur = s.pop();
        output.push(cur); //把棧頂元素添加到第二個stack
        
        if(cur.left != null){
            s.push(cur.left);
        }
        if(cur.right != null){
            s.push(cur.right);
        }
        
        while(!output.isEmpty()){//遍歷輸出第二個stack,即爲後序遍歷
            System.out.print(output.pop().val + " ");
        }
    } 
}
相關文章
相關標籤/搜索