判断二叉树是否对称

  1. left == null && right == null: true
  2. left != null && right != null:
    1. left.val == right.val
    2. isTree(left.left, right.right) && isTree(left.right, right.left)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return bool布尔型
     */
    public boolean isSymmetric (TreeNode root) {
        // write code here
        if(root == null) 
            return true;
        TreeNode left = root.left;
        TreeNode right = root.right;
        return isTree(left, right);
    }
    // dfs:判断左右子树
    public boolean isTree (TreeNode left, TreeNode right) {
        if(left == null && right == null)
            return true;
        if(left != null && right != null) {
            if(left.val != right.val)
                return false;
            return isTree(left.left, right.right)
                && isTree(left.right, right.left);
        }
        return false;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值