ในแนวทาง recursive เพื่อหาว่า tree เป็น symmetric หรือไม่ เราเริ่มตรวจสอบว่า tree เป็น null หรือไม่ หาก tree เป็น null ถือว่า symmetric หาก tree ไม่ใช่ null เราเรียกเมธอด isSymmetricMirror ใน isSymmetricMirror เราเอาค่าลูกซ้ายและลูกขวา หากลูกซ้ายและลูกขวาเป็น null ทั้งคู่ ถือว่า symmetric หากค่าใดค่าหนึ่งเป็น null ถือว่าไม่ symmetric และสุดท้ายเราเรียก isSymmetric แบบ recursive โดยส่งค่าลูกซ้ายและลูกขวา
ตัวอย่าง
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