二叉樹的遍歷 (迭代法)

Borris發表於2020-02-08

Bianry Tree 的遍歷分為中序,前序和後序。遍歷順序分別為:中-左-右,左-中-右,左-右-中。

遞迴實現遍歷的方法非常簡單直接,所以本文不再贅述。下面討論的是迭代法實現二叉樹遍歷。

定義 TreeNode:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

中序遍歷 左-中-右

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>(); // Store the traversal result
        if (root == null) {
            return res;
        }

        TreeNode curr = root; // Pointer to traverse the tree
        Stack<TreeNode> stack = new Stack<>();
        while (curr != null || !stack.isEmpty()) {
            while (curr != null) { // Keep push the left node into stack
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            res.add(curr.val); // 將當前值加入 list
            curr = curr.right; // Move to the right node
        }

        return res;
    }
}

和中序遍歷的做法一樣,利用棧模擬遞迴。先將值加入 list,然後訪問左子樹,如果左子樹為空了,再訪問右子樹。

前序遍歷 中-左-右

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>(); // Store the traversal result
        if (root == null) {
            return res;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;

        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                res.add(curr.val); // 將當前值加入 list
                stack.push(curr);
                curr = curr.left;
            } else {
                curr = stack.pop(); // 節點為空,父節點出棧
                curr = curr.right;
            }   
        }
        return res;
    }
}

還有一種做法是左右子樹分別壓棧, 要注意的是,由於我們要先訪問左子樹,所以壓棧就需要先壓右子樹,再壓左子樹。

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>(); // Store the traversal result
        if (root == null) {
            return res;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            if (curr == null) {
                continue;
            }
            res.add(curr.val);
            stack.push(curr.right);
            stack.push(curr.left);
        }
        return res;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章