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());
}
}
輸出是什麼?你能向我們展示你的主要內容嗎? –
更新了帶有主函數的類的問題。 –
你自己實現了BinaryTreeNode嗎? –