如何使用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP