ในแนวทางวนซ้ำ เราต้องสร้าง 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