I just started my second C++ class and am struggling to grasp the concept of nodes and linked lists. Every insert function I've found for binary trees uses either an int as a parameter, or an int an a node. Example:
Node* InsertNode(Node* root, int data)
{
// If the tree is empty, assign new node address to root
if (root == NULL) {
root = CreateNode(data);
return root;
}
// Else, do level order traversal until we find an empty
// place, i.e. either left child or right child of some
// node is pointing to NULL.
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL)
q.push(temp->left);
else {
temp->left = CreateNode(data);
return root;
}
if (temp->right != NULL)
q.push(temp->right);
else {
temp->right = CreateNode(data);
return root;
}
}
But this practice problem requires two nodes as parameters.
function (Insert(Node *insert_node, Node *tree_root){
}
This is the full code:
#include <iostream>
#include <cstddef>
using std::cout;
using std::endl;
class Node {
int value;
public:
Node* left; // left child
Node* right; // right child
Node* p; // parent
Node(int data) {
value = data;
left = NULL;
right = NULL;
p = NULL;
}
~Node() {
}
int d() {
return value;
}
void print() {
std::cout << value << std::endl;
}
};
int main(int argc, const char * argv[])
{
}
function insert(Node *insert_node, Node *tree_root){
//Your code here
}
function delete_node(int value, Node *tree_root){
//Your code here
}
function search(int value, Node *tree_root){
//Your code here
}
I don't know why I'm struggling with these concepts so much. Can anyone point out the right direction?
You have Node
objects with a member called data
which is an int
.
You have not given your full insert (with numeric parameter), so I will only give you an idea of how you can refactor that:
int data = insert_node->data;
, so later on data
will have the correct value temp->left = CreateNode(data);
or temp->right = CreateNode(data);
, you will need temp->left = insert_node;
and temp->right = insert_node;
, respectively, as you already have a node to work with, no need to create one tree_root
, earlier it was called root
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.