我尝试为静态二进制树创建一个数据结构,其中包含一个静态根值和两个子节点。我试图让它为任意数量的子值动态化。如何使用静态根节点执行此操作。如果我采用myArray = {3,11,8,18,21,36,1},我该如何实现。任何没有复杂代码更改的简单代码都会有所帮助。
class Program
{
static void Main(string[] args)
{
TreeNode rootNode = new TreeNode();
rootNode.value = 9;
int[] myArray = { 3, 11 };
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i] > rootNode.value)
{
//add to right node
TreeNode right = new TreeNode();
right.value = myArray[i];
rootNode.rightNode = right;
}
else
{
//add to left node
TreeNode left = new TreeNode();
left.value = myArray[i];
rootNode.leftNode = left;
}
}
}
}
class TreeNode
{
public int value { get; set; }
public TreeNode leftNode { get; set; }
public TreeNode rightNode { get; set; }
}
答案 0 :(得分:1)
嘿,这段代码运行正常但你可以根据需要进一步改进。对不起,但我不得不做一点冗长。希望你理解代码。这并不困难。顺便提一句,代码在java中。只需将语法更改为c#。
class Program
{
static void Main(string[] args)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the number of childs!");
int input = a.nextInt();
TreeNode rootNode = new TreeNode();
TreeNode parent = rootNode;
rootNode.value = 9;
parent.childNodes = new TreeNode[input];
for(int i = 0; i< input; i++){
parent.childNodes[i] = new TreeNode();
parent.childNodes[i].value = 0;
}
parent.hasChild = true;
int count = 1;
int startingIndex = 0;
int EndingIndex = input - 1;
int next = 0;
int[] myArray = { 19, 11, 12, 13 ,14, 15 };
for (int i = 0; i < myArray.length; i++)
{
if(count <= input){
if (myArray[i] > parent.value)
{
//add to right node
parent.childNodes[EndingIndex].value = myArray[i];
EndingIndex--;
count++;
}
else
{
//add to the left node
parent.childNodes[startingIndex].value = myArray[i];
startingIndex++;
count++;
}
}
else{
parent = parent.childNodes[next];
parent.childNodes = new TreeNode[input];
for(int j = 0; j< input; j++){
parent.childNodes[j] = new TreeNode();
parent.childNodes[j].value = 0;
}
parent.hasChild = true;
next++;
count = 1;
i--;
startingIndex = 0;
EndingIndex = input - 1;
next = 0;
}
}
parent = rootNode;
TreeNode grandparent = parent;
System.out.println("root Node: " + parent.value);
next = 0;
int childs = 1;
while(parent.hasChild == true){
for(int i=0; i<input; i++){
if(parent.childNodes[i].value != 0){
System.out.print("child " + childs + " : ");
childs++;
System.out.print(parent.childNodes[i].value);
System.out.println();
}
}
childs = 1;
System.out.println();
parent = grandparent.childNodes[next];
next++;
}
}
}
class TreeNode
{
public int value;
TreeNode[] childNodes;
boolean hasChild = false;
}