如何在 C# 中使用递归检查树是否对称?
在递归方法中,我们找到一棵树是否对称,我们首先检查树是否为空,如果树为空则其对称,如果树不为空,我们调用方法issymmetricmirror。在isSymmetricMirror中,我们得到左孩子和右孩子的值,如果左孩子和右孩子都为空,我们认为是对称的,如果其中一个值为空,那么我们认为不是对称的,最后我们通过传递左右递归调用issymmetric方法孩子的价值观。
示例
public class TreesPgm{
public class Node{
public int Value;
public Node LeftChild;
public Node RightChild;
public Node(int value){
this.Value = value;
}
public override String ToString(){
return "Node=" + Value;
}
}
public bool isSymmetricRecursive(Node node)
{
if (node == null){
return true;
}
return isSymmetricMirror(node.LeftChild, node.RightChild);
}
private bool isSymmetricMirror(Node node1, Node node2){
if (node1 == null && node2 == null){
return true;
}
if (node1 == null || node2 == null){
return false;
}
if (node1.Value != node2.Value){
return false;
}
return isSymmetricMirror(node1.LeftChild, node2.RightChild) && isSymmetricMirror(node2.LeftChild, node1.RightChild);
}
}输出结果 1
2 2
3 4 4 3
True热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下