ในแนวทางแบบเรียกซ้ำ เราจะพบว่าต้นไม้มีความสมมาตรหรือไม่ ขั้นแรกเราจะตรวจสอบว่าต้นไม้นั้นเป็นโมฆะหรือไม่ ถ้าต้นไม้นั้นเป็นโมฆะ แสดงว่ามีความสมมาตร หากต้นไม้ไม่เป็นโมฆะ เราเรียกว่า amethod 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