判断二叉树是否对称

从根节点开始检测二叉树

  • 左右节点是否都为空
  • 是否其中一个为空
  • 是否两个都不为空,但左右节点值不等
  • 是否两个都不为空,但左右节点值相等,递归调用
function Tree(pTree) {
    if (!pTree) {
        return true;
    }
    return TreeJug(pTree.left, pTree.right);
}

function TreeJug(left, right) {
    if (!left && left === right) {
        return true;
    }
    if (!left || !right) {
        return false;
    }
    if (left.val !== right.val) {
        return false;
    }
    return TreeJug(left.left, right.right) && TreeJug(left.right, right.left);
}
let tree = {
    val: 1,
    left: null,
    right: null
};
console.log(Tree(tree));

 

好的,下面是用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、付费专栏及课程。

余额充值