如何在 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 Q1 = new Queue);
Queue Q2 = new Queue();
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热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练