如何使用 C# 中的遞迴反轉二叉查詢樹?


要反轉二叉查詢樹,我們呼叫一個方法 InvertABinarySearchTree,它將節點作為引數。如果節點為 null,則返回 null,如果該節點不為 null,則透過傳遞左右子代的值遞迴地呼叫 InvertABinarySearchTree。並將右子值分配給左子值並將左子值分配給右子值。最終的輸出將包含一個樹,它將是其自身的映象。

示例

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 Node InvertABinarySearchTree(Node node){
      if (node == null){
         return null;
      }
      Node left = InvertABinarySearchTree(node.LeftChild);
      Node right = InvertABinarySearchTree(node.RightChild);
      node.LeftChild = right;
      node.RightChild = left;
      return root;
   }
}

輸入

   1
  3 2

輸出

   1
  2 3

於: 2021 年 8 月 17 日更新

1K+ 次瀏覽

開始您的 職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.