树的中序遍历

递归法

public void inOrder(Node root) {
        if (root == null) {
            return;
        }
        // 先遍历左子树
        inOrder(root.left);
        // 遍历根
        System.out.printf("%d ", root.data);
        // 遍历右子树
        inOrder(root.right);
    }

非递归法

private List<Integer> inOrderUnRecur(Node root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        LinkedList<Node> stack = new LinkedList<>();
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                list.add(root.data);
                root = root.right;
            }
        }
        return list;

显式的使用栈,先遍历树的左子树再访问根,最后访问右子树。

点赞