如何使用 C# 中的迭代来检查这棵树是否是对称的?
在迭代方法中,我们必须创建 2 个队列,一个队列保存左子节点,另一个队列保存右子节点的值。如果树为空,则它对称于穿过其根节点的垂直轴。否则,检查两个子树的根节点的值是否相同。如果相同,则检查左子树和右子树是否对称。将左子节点值和右子节点值入队到队列 1,并将右子节点和左子节点值入队到队列 1
示例
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 isSymmetricIterative(Node node){
if (node == null){
return true;
}
Queue<Node> Q1 = new Queue<Node>);
Queue<Node> Q2 = new Queue<Node>();
Q1.Enqueue(node.LeftChild);
Q2.Enqueue(node.RightChild);
while (Q1.Count > 0 && Q2.Count > 0){
Node n1 = Q1.Dequeue();
Node n2 = Q2.Dequeue();
if ((n1 == null && n2 != null) || n1 != null && n2 == null){
return false;
}
if (n1 != null){
if (n1.Value != n2.Value){
return false;
}
Q1.Enqueue(n1.LeftChild);
Q1.Enqueue(n1.RightChild);
Q1.Enqueue(n1.RightChild);
Q1.Enqueue(n1.LeftChild);
}
}
return true;
}
}输出
1 2 2 3 4 4 3 True
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP