LeetCode Hot100 Day3

LeetCode刷题日记 约 3.8 千字
二叉树的中序遍历

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

思路:

中序:左-中-右;只需要一直向左走,走到头再回头向右,用递归很简单。

代码:

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inorder(root, result);
        return result;
    }

    private void inorder(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }
        inorder(node.left, result);   // 1. 遍历左子树
        result.add(node.val);         // 2. 访问根节点
        inorder(node.right, result);  // 3. 遍历右子树
    }
}
对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false

提示:

  • 树中节点数目在范围 [1, 1000] 内
  • -100 <= Node.val <= 100

思路:

对称情况:

  1. 都为空
  2. 非空且值相同

非对称情况:

  1. 只有其中一个为空
  2. 值不同

代码:

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

    // 判断 l 和 r 两棵子树是否互为镜像
    private boolean isMirror(TreeNode l, TreeNode r) {
        // 都空 → 对称
        if (l == null && r == null) return true;
        // 只有一个空 → 不对称
        if (l == null || r == null) return false;
        // 值相等 且 交叉递归
        return l.val == r.val
                && isMirror(l.left, r.right)
                && isMirror(l.right, r.left);
    }
}