二叉树的遍历 (迭代法)

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 协议》,转载必须注明作者和本文链接
讨论数量: 1

感觉代码简洁性上还可以优化

4年前 评论
zyfsuzy (作者) 4年前
Borris (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!