이진 검색 트리를 반전시키기 위해 노드를 매개변수로 사용하는 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