这个项目的目的是从用户那里获取一个数组并使用它来创建一个使用节点的树。下一步是调用一个方法来检查它是否代表二叉树。我已经工作了好几个小时,似乎无法找到正确的检查方法。
到目前为止,这是我的代码。我已经完成了除isBinaryTree()
方法以外的所有方法来检查它是否是二叉树。
import java.util.Scanner;
public class TestBinaryTree
{
Node root;
public void addNode(int key)
{
Node newNode = new Node(key);
if(root == null)
{
root = newNode;
}
else
{
Node focusNode = root;
Node parent;
while(true)
{
parent = focusNode;
if(key < focusNode.key)
{
focusNode = focusNode.leftChild;
if(focusNode == null)
{
parent.leftChild = newNode;
return;
}
}
else
{
focusNode = focusNode.rightChild;
if(focusNode == null)
{
parent.rightChild = newNode;
return;
}
}
}
}
}
/*public static boolean isBinaryTree(int rt, int lft, int rght)
{
}*/
public static void main(String[] args)
{
int Nroot, Nleft, Nright;
Scanner input = new Scanner(System.in);
TestBinaryTree theTree = new TestBinaryTree();
System.out.println("How many numbers are in the array: ");
int num = input.nextInt();
int arr[]=new int[num];
System.out.println("Enter the numbers: ");
for(int i=0;i<num;i++)
{
arr[i] = input.nextInt();
theTree.addNode(arr[i]);
}
}
}
class Node
{
int key;
Node leftChild;
Node rightChild;
Node(int key)
{
this.key = key;
}
public String toString()
{
return "Node: " + key;
}
}