JZ58 对称的二叉树

30 篇文章 1 订阅
27 篇文章 0 订阅

题目描述

请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

  • 示例1
//输入
{8,6,6,5,7,7,5} // 8,6,6
// 返回值
true
  • 示例2
//输入
{8,6,9,5,7,7,5} // 8,6,9
// 返回值
false

题解

思路一:递归

把输入的树看成两棵树,一个遍历左子树,另一个表来遍历右子树,然后逐一比较遍历结果。

  1. 设置一个递归函数isSame(r1, r2),表示如果对称,返回true,否则返回false
  2. 递归终止条件:r1==nullptr && r2==nulllptr, 直接返回true,否则,如果只有一个为nullptr,返回false
  3. 下一步递归:如果r1->val == r2->val, 则isSame(root1->left, root2->right) && isSame(root1->right, root2->left);
    在这里插入图片描述
  • C#:
/*
public class TreeNode
{
    public int val; // 树子节点的值
    public TreeNode left; //左指针
    public TreeNode right; //右指针
    public TreeNode (int x)
    {
        val = x;
    }
}*/

递归函数isSame(TreeNode pRoot1, TreeNode pRoot2)

class Solution
{
    public bool isSymmetrical(TreeNode pRoot)
    {
        // write code here
        return isSame(pRoot, pRoot);
    }
    bool isSame(TreeNode pRoot1, TreeNode pRoot2)
    {
        if (pRoot1 == null && pRoot2 == null) // 输入树为空, 返回true
        {
            return true;
        }
        if (pRoot1 == null || pRoot2 == null) // 输入树为空的情况在上一部分已经return
        {
            return false;
        }
        if (pRoot1.val != pRoot2.val)
        {
            return false;
        }
        return isSame(pRoot1.left, pRoot2.right) && isSame(pRoot1.right, pRoot2.left);
    }
}

重载函数 isSymmetrical(TreeNode pRoot1, TreeNode pRoot2)

class Solution
{
    public bool isSymmetrical(TreeNode pRoot)
    {
        // write code here
        return isSymmetrical(pRoot, pRoot);
    }
    bool isSymmetrical(TreeNode pRoot1, TreeNode pRoot2)
    {
        if (pRoot1 == null && pRoot2 == null)
        {
            return true;
        }
        if (pRoot1 == null || pRoot2 == null)
        {
            return false;
        }
        if (pRoot1.val != pRoot2.val)
        {
            return false;
        }
        return isSymmetrical(pRoot1.left, pRoot2.right) && isSymmetrical(pRoot1.right, pRoot2.left);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值