W
e
l
c
o
m
e
: )

每日一题:判断一颗二叉树是否是镜面树

题目描述:判断一颗二叉树是否是镜面树,说白了就是这棵树是否是按照中轴左右对称的。

/**
 * 测试链接:https://leetcode.com/problems/symmetric-tree
 * 题目描述:判断一颗二叉树是否是镜面树
 */
public class Code02_SymmetricTree {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
    }

    public static boolean isSymmetric(TreeNode root) {
        return isMirror(root, root);
    }

    /**
     * h1和h2是同一棵树,只是一个往左走,一个往右走
     * @param h1
     * @param h2
     * @return
     */
    public static boolean isMirror(TreeNode h1,TreeNode h2){
        if (h1 == null ^ h2 == null){
            return false;
        }
        if (h1 == null && h2 == null){
            return true;
        }
        return h1.val == h2.val && isMirror(h1.left,h2.right) && isMirror(h1.right,h2.left);
    }
}
posted @ 2026-07-30 08:34  寒月静无光  阅读(3)  评论(0)    收藏  举报