力扣---剑指 Offer 28. 对称的二叉树

发布时间 2023-03-27 14:19:41作者: allWu

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

示例 1:

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

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

限制:

0 <= 节点个数 <= 1000

注意:本题与主站 101 题相同:https://leetcode-cn.com/problems/symmetric-tree/

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/dui-cheng-de-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


 

很容易就想到先判断树是否为空,然后同时遍历树的左右节点(深度优先或者广度优先都可以,只不过一个是先左子树,另一个是先右子树)。

判断为true或false的条件有三个:

1. 如果两个节点都为null,说明到了叶子,对称,返回true。

2. 如果有一个节点为null,说明不对称,返回false。

3. 如果两个节点的val不相等,说明不对称,返回false。

这里用的是递归写法(深度优先遍历)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        // 如果一开始的节点为null,则说明对称
        if (root == null) {
            return true;
        }
        // 同时遍历左右子树,如果判断是否对称。
        return comparse (root.left, root.right);
    }
    private boolean comparse(TreeNode tree1, TreeNode tree2) {
        // 都为null说明到了叶子节点,对称。
        if (tree1 == null && tree2 == null) {
            return true;
        }
        // 只有一个为null说明不对称。
        if (tree1 == null || tree2 == null) {
            return false;
        }
        // val不相等,说明不对称。
        if (tree1.val != tree2.val) {
            return false;
        }
        // 需要两边都对称才可以,用&&连接。
        return comparse (tree1.left, tree2.right) && comparse (tree1.right, tree2.left);
    }
}