判断二叉树是否对称

题目描述

给定一棵二叉树,判断琪是否是自身的镜像(即:是否对称)
例如:下面这棵二叉树是对称的
     1
    /  \
  2    2
 / \    / \
3 4  4  3
下面这棵二叉树不对称。
    1
    / \
  2   2
    \    \
    3    3
备注:
希望你可以用递归和迭代两种方法解决这个问题

示例1

输入

{1,2,2}

输出

true

示例2

输入

{1,2,3,3,#,2,#}

输出

false
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    bool tryFind(TreeNode* lch, TreeNode* rch){
        if(!lch && !rch){
            return true;
        }
        if((!lch && rch) || (lch && !rch)){
            return false;
        }
        return tryFind(lch->left, rch->right) 
            && tryFind(lch->right, rch->left)
            && (lch->val == rch->val);
    }
    bool isSymmetric(TreeNode* root) {
        // write code here
        if(root == NULL){
            return true;
        }
        return tryFind(root->left, root->right);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值