Leetcode 101. Symmetric Tree 验证树的对称性 解题报告

本文介绍了一种判断二叉树是否对称的有效方法。通过对二叉树的左右子树进行递归比较,确保每一对对应的节点值相等且结构镜像对称。通过简单的逻辑调整,将传统的相同树判断算法转化为对称性判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 解题思想

这道题是上一道题的延伸版。
首先,题目的意思是说给了一颗树,让我们判断他是否是对称的(以根节点为中心,镜像颠倒而成)

其实解题方式也很简单,把根节点的左右节点开始,当做两个独立的子树,判断这两个子树的是否对称

而判断这两个子树是否对称,就是在判断两个子树的那个算法那里,把原来的左左对比,右右对比,改成左右对比和右左对比就可以了,稍稍改动一下位置就可以

Leetcode 100. Same Tree 验证树是否相同 解题报告

2 原题

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 
    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:
    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively. 

3 AC解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 /**
  * 当成两棵树遍历检查就可以了
  * */
public class Solution {
    public boolean check(TreeNode leftPart,TreeNode rightPart){
        if(leftPart==null && rightPart==null)
            return true;
        if(leftPart==null || rightPart==null)
            return false;
        if(leftPart.val != rightPart.val)
            return false;
        return check(leftPart.right,rightPart.left) && check(leftPart.left,rightPart.right);
    }
    public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        return check(root.left,root.right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值