如何使用 C# 中的递归检查树是否对称?


在递归方法中,我们要查找一棵树是否对称,我们首先检查这棵树是否为空,如果树为空,则它就是对称的;如果树不为空,我们调用一种方法 issymmetricmirror。在 isSymmetricMirror 中,我们获取左子树和右子树的值,如果左右子树都为空,我们认为是对称的;如果其中一个值为 null,我们认为是不对称的;最后,我们通过传递左右子树的值递归地调用 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

更新于: 17-8-2021

157 次浏览

开启您的职业生涯

完成课程以取得认证

开始
广告
© . All rights reserved.