如何使用 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

更新時間: 2021 年 8 月 17 日

120 次瀏覽

開啟你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.