题目

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

例如,二叉树 [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

代码

  • 递归左节点等于右节点
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        return helper(root.left, root.right);
    }

    public boolean helper(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null)
            return true;
        if (root1 == null || root2 == null)
            return false;
        return root1.val == root2.val && helper(root1.left, root2.right) &&
            helper(root1.right, root2.left);
    }
}

代码分析:一个好的思路实在太重要了。关键代码:

return root1.val == root2.val && helper(root1.left, root2.right) &&
       helper(root1.right, root2.left);

在 helper() 中传入 (root1.left, root2.right)helper(root1.right, root2.left),递归实现整体的左右结点比较。

本文题目dui-cheng-de-er-cha-shu-lcof

最后修改:2022 年 01 月 13 日 03 : 30 PM
如果我的文章对你有用,请随意赞赏