Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธี Invert Binary Search Tree ด้วย Recursion ใน C#


เพื่อ Invert Binary Search Tree เราเรียกเมธอด InvertABinarySearchTree ที่รับ node เป็นพารามิเตอร์ หาก node เป็น null คืนค่า null หาก node ไม่ใช่ null เราเรียก InvertABinarySearchTree แบบ recursive โดยส่งค่าลูกซ้ายและลูกขวา และกำหนดค่าลูกขวาให้ลูกซ้าย และค่าลูกซ้ายให้ลูกขวา ผลลัพธ์สุดท้ายจะเป็น tree ที่เป็น鏡像ของตัวเอง

ตัวอย่าง

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