1
私は最近、データ構造とアルゴリズムの学習を始めました。私はツリーの左側にのみノードを追加しているバイナリツリーを作成しています。どのように私はそれがルートノードの両側にノードを追加し、次のようになりますように作成することができます。ノードを左側に追加するバイナリツリー。ルートノードの左右両方でどのように動作させることができますか?
2
/\
/ \
/ \
/ \
7 5
/\ /\
/ \ / \
2 6 3 6
ここで私が書いたコードです:
public class BinaryTreeOperations {
BinaryTreeNode root;
//let's start with an empty binary tree
public BinaryTreeOperations(){
root = null;
}
//let's initialize our tree with a root node
public BinaryTreeOperations(BinaryTreeNode rootNode){
this.root = rootNode;
}
public void insert(int data)
{
root = insertNode(root, data);
}
private BinaryTreeNode insertNode(BinaryTreeNode node, int data){
//To check if the root is null then create a root node with no children
if (node == null) {
System.out.println("inserting root node"+ data+"\n");
node = new BinaryTreeNode(data);
}
else {
if(node.getRightChild() == null){
System.out.println("inserting right child :"+data+"\n");
node.rightChild=insertNode(node.rightChild, data);
}
else {
System.out.println("inserting left child :"+data+"\n");
node.leftChild = insertNode(node.leftChild, data);
}
}
return node;
}
public int countNodes() {
return countNodes(root);
}
private int countNodes(BinaryTreeNode r) {
if (r == null)
return 0;
else
{
int count = 1;
count += countNodes(r.getLeftChild());
count += countNodes(r.getRightChild());
return count;
}
}
}
メインクラス:
public class BinaryTreeMain {
public static void main(String args[]){
BinaryTreeOperations binaryTreeOperations = new BinaryTreeOperations();
binaryTreeOperations.insert(12);
binaryTreeOperations.insert(17);
binaryTreeOperations.insert(11);
binaryTreeOperations.insert(21);
binaryTreeOperations.insert(27);
System.out.println("Total number of nodes :" + binaryTreeOperations.countNodes());
}
}
出力は何ですか?もしあなたがもしあれば私たちにあなたを見せてもらえますか? –
main関数を持つクラスで質問を更新しました。 –
BinaryTreeNodeを自分で実装しましたか? –