[英]Binary Search Tree Insertion C++ rooted at current node
只需要添加項目,我需要將項目添加到二叉樹中。
這是我給出的代碼:
void BinaryTree::add(Data * data) {
if (root == NULL) {
root = new BinaryTreeNode(data);
}
else {
root->add(data);
}
}
其中root
是BinaryTree
的私有變量,定義為BinaryTreeNode
。
我需要實現一個方法:
void BinaryTreeNode::add(Data * data);
其中BinaryTreeNode
是:
class BinaryTreeNode {
public:
Data * nodeData;
BinaryTreeNode * left;
BinaryTreeNode * right;
/**
* Constructor
*/
BinaryTreeNode(
Data * data,
BinaryTreeNode * left = NULL,
BinaryTreeNode *right = NULL
)
: nodeData(data), left(left), right(right)
{ }
// ...
我想以遞歸方式執行此操作,但是當您僅傳遞要添加的數據時,我並不樂觀。
我的想法不起作用是:
void BinaryTreeNode::add(Data * newData) {
BinaryTreeNode * temp = this;
if (temp == NULL) {
temp->nodeData = newData;
} else {
if (newData->compareTo(nodeData) < 0) {
temp->left->add(newData);
} else {
temp->right->add(newData);
}
}
}
您正在為此設置臨時值,然后將其與NULL進行比較。 這永遠不應該是NULL。 您需要檢查左側和右側是否為NULL。
那么一個二叉樹,至少我知道如何實現涉及到如下所示的兩個對象,一個包含treenode對象,另一個作為整個樹的接口。
class cBinaryTree {
public:
bool insert(int inData);
//Other operations
private:
cBinaryTreeNode* root;
bool leftInsertion;
cBinaryTreeNode* getRoot() { return root; }
當您比較輸入數據的實際值並相應地放置它時,這有資格作為二叉搜索樹。 然后插入函數可以寫成
bool cBinaryTree::insert(int inData) {
//handle case if its first node.
cBinaryTreeNode *Parent = getInsertionNodePosition(getRoot(), inData);
cBinaryTreeNode *newNode = createNewNode(inData);
if(leftInsertion) //insert into left. add return statement
Parent->setLeftChild() = newNode;
else //insert into right
}
遞歸查找函數將是類似的
cBinaryTreeNode* getInsertionNodePosition(cBinaryTreeNode* node,int inData) {
//Check left subtree and proceed from there.
if(inData < node->getData()) {
if(node->getLeftChild() == NULL) {
leftInsertion = true;
return node;
}
else {
node = node->getLeftChild();
return getInsertionNodePosition(node, inData);
}
}
//Similarly Check right subtree.
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.