遍歷二叉樹的遞歸解法與非遞歸解法

樹結點定義:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}

前序遍歷(根->左->右)

遞歸解法:

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

    // 輔助stack  
    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);
        }
    }
}  

 

中序遍歷和後續遍歷都與前序遍歷類似,僅訪問根節點的順序不同。

 

分層遍歷:

使用隊列實現。分別將根結點、左結點、右結點入隊,然後逐個出隊即可。

public static void levelTraversal(TreeNode root) {
    if (root == null) {
        return;
    }
    LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
    queue.push(root);

    while (!queue.isEmpty()) {
        TreeNode cur = queue.removeFirst();
        System.out.print(cur.val + " ");
        if (cur.left != null) {
            queue.add(cur.left);
        }
        if (cur.right != null) {
            queue.add(cur.right);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章