代码随想录Day15 | 102. 二叉树的层序遍历、226. 翻转二叉树、101. 对称二叉树 | 二叉树、递归

47 阅读1分钟

102. 二叉树的层序遍历

题目链接:102. 二叉树的层序遍历

思路: 层序遍历还是比较简单的,用一个队列即可实现。挨个遍历每一层的节点,并把每个节点的子节点加入队列。

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            int len = q.size();
            List<Integer> list = new LinkedList<>();

            while (len > 0) {
                TreeNode cur = q.poll();
                list.add(cur.val);
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
                len--;
            }
            res.add(list);
        }
        return res;
    }
}

总结:

相邻两个元素相关的问题可以使用栈来解决

226. 翻转二叉树

题目链接:226. 翻转二叉树

思路: 把二叉树上的每个节点的左右子节点都交换一下,可以用前序或后序来遍历,但是中序不可以。

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        traverse(root);
        return root;
    }

    public void traverse(TreeNode root) {
        if (root == null) {
            return;
        }

        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        
        traverse(root.left);
        traverse(root.right);
    }
}

总结:

101. 对称二叉树

题目链接:101. 对称二叉树

思路:

需要使用后序遍历,因为中节点需要知道左右节点的信息才能判断是否相等。参数为左右两个节点,比较左节点的左节点和右节点的右节点(外侧),再比较左节点的右节点和右节点的左节点(内侧)。

我的代码:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return check(root.left, root.right);
    }

    boolean check(TreeNode left, TreeNode right) {
        if (left == null || right == null) {
            return left == right;
        } else if (left.val != right.val) {
            return false;
        }

        boolean outside = check(left.left, right.right);
        boolean inside = check(left.right, right.left);
        
        // 后序遍历位置
        boolean result = outside && inside;
        return  result;
    }
}

总结:

复习层序遍历和二叉树的递归操作,注意遍历顺序。