判断二叉树是否对称

解题思路:首先判断特殊情况,比如左右子树是否为一空一有,是否为两空,是否相等,然后递归判断外侧是否相等(即为左子树的左节点和右子树的右节点)和内侧是否相等(即为右子树的左节点和左子树的右节点)

具体代码:

class Solution {

public:

   bool  compare(TreeNode *left,TreeNode*right)

   {

      if(left==NULL&&right!=NULL)return false;

      else if(right==NULL&&left!=NULL)return false;

      else if(right==NULL&&left==NULL)return true;

      else if(right->val!=left->val)return false;

      bool outside=compare(left->left,right->right);

      bool  inside=compare(left->right,right->left);

      bool result=(outside&&inside);

      return result;

   }

    bool isSymmetric(TreeNode* root) {

  return compare(root->left,root->right);  

    }

};

题目如下:

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

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

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是用C#语言生成一棵树(二叉链表)的示例代码,并且实现判断该树是否对称二叉树的功能: ``` using System; class Node { public int data; public Node left, right; public Node(int value) { data = value; left = right = null; } } class BinaryTree { Node root; public BinaryTree() { root = null; } private bool isSymmetric(Node left, Node right) { if (left == null && right == null) return true; if (left == null || right == null) return false; return (left.data == right.data) && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); } public bool isSymmetric() { if (root == null) return true; return isSymmetric(root.left, root.right); } static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(2); tree.root.left.left = new Node(3); tree.root.left.right = new Node(4); tree.root.right.left = new Node(4); tree.root.right.right = new Node(3); if (tree.isSymmetric()) Console.WriteLine("The tree is symmetric"); else Console.WriteLine("The tree is not symmetric"); } } ``` 这段代码中,我们首先定义了一个节点类`Node`,其中包含了节点的值、左子节点和右子节点。接着,我们定义了一个二叉树类`BinaryTree`,其中包含了二叉树的根节点和判断二叉树是否对称的核心函数`isSymmetric`。这个函数采用递归的方式,判断左右子树是否对称同构。 在`Main`函数中,我们创建了一棵树,并调用了`isSymmetric`函数来判断该树是否对称二叉树。如果是,则输出"The tree is symmetric";否则,输出"The tree is not symmetric"。 希望这段代码能够帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值