Function for inserting a value in binary tree? - c++

I have a function insert that is used to insert values into the Binary tree.
But when I log out the value nothing is shown.
I'm aware of the insertion using member function.
The root node's value is not being updated?
Could someone tell me where I'm going wrong?
#include <iostream>
using namespace std;
class Node{
public:
int value;
Node* left;
Node* right;
Node();
Node(int data){
value = data;
left = NULL;
right = NULL;
}
};
void insert(Node* root , int val){
if(root == NULL){
root = new Node(val);
return;
}
if(root->value > val)
insert(root->left,val);
else
insert(root->right,val);
}
int main()
class Node* root = NULL;
insert(root,5);
cout<<root->value;
}

you are inserting position on the right place but the problem is you are not creating the link of your newly inserted node to it's parent.
you can check this as reference!

Related

C++ binary tree object, "insert" method with 1 parameter

I'm learning binary trees and want to implement with OOP where I have a struct Node and create a BST Object. I'm trying to create an insert function with this approach and am running into the issue where I can't recursively traverse the tree to add a new node - that is, unless I overload the method, essentially copying it, to call the new method with a pointer to left or right. Hard to explain, but right now I have two methods, and I'm not sure if I'm missing something obvious to just have 1 method with 1 parameter int data, or if this approach just isn't correct. I feel like there's something valuable for me to learn here. Many thanks.
#include <iostream>
struct Node
{
Node *right;
Node *left;
int data;
};
class BST
{
public:
Node* root;
public:
BST()
:root(NULL)
{
}
//inserts node taking parameter data
Node* insertNode(int data)
{
//if tree is empty, create root
if (root == NULL)
{
root = newNode(data);
}
//if data is smaller than or equal to root, insert left
else if (data <= root->data)
{
root->left = insertNode(root->left, data);
}
//data is larger than root, insert right
else
{
root->right = insertNode(root->right, data);
}
return root;
}
//inserts new node
Node* insertNode(Node *root, int data)
{
//if tree is empty, create root
if (root == NULL)
{
root = newNode(data);
}
//if data is smaller than or equal to root, insert left
else if (data <= root->data)
{
root->left = insertNode(root->left, data);
}
//data is larger than root, insert right
else
{
root->right = insertNode(root->right, data);
}
return root;
}
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
};
int main() {
BST bst1;
bst1.insertNode(30);
bst1.insertNode(15);
return 0;
}
You can save the redundancy by having one call forward to the other:
Node* insertNode(int data)
{
return insertNode(root, data);
}
Note that having identical names for your class member (Node* root) and the local variable in Node* insertNode(Node *root, int data) is error-prone.
Also please do not forget to delete what you new.

Unable to change the pointer value in class

I am trying to build a BST in C++, the root node inside class was not affecting when in call insert() function, it remains NULL.
I am passing root to insert_tree() function when I need to insert data into the tree but when I try to print root value inside insert_tree it always returning NULL
#include <iostream>
struct node
{
int value;
node *left;
node *right;
};
class bst
{
private:
node *root;
node* insert(node* parent,int value)
{
if(parent== NULL){
parent = new node;
parent->value = value;
parent->left = parent->right = NULL;
}
else if(parent->value>value){
parent->left = insert(parent->left,value);
}
else{
parent->right=insert(parent->right,value);
}
return parent;
}
void display(node* parent){
if(parent != NULL){
display(parent->left);
std::cout << parent->value <<"\t";
display(parent->right);
}
}
public:
bst(){
root = NULL;
}
void insert(int value){
root = insert(root,value);
}
void display(){
display(root);
}
};
int main(int argc, char const *argv[])
{
bst b1;
b1.insert(10);
b1.insert(1);
b1.insert(11);
b1.insert(9);
b1.display();
return 0;
}
I would suggest you read about BST first here and learn how insertion is done in a BST. First of all the algorithm is wrong and secondly, use pass by reference in insert_tree() function instead of pass by value. As you are passing by value, so the value of root doesn't change.

Why doesn't this swap the two nodes?

I am trying to solve a question from leetcode - deleting a node from a BST. We would be given the root node of a BST and a key; and we have to deleted the node with that key as the value. We can assume that all the tree nodes have unique values. We have to return the root node post this operation. (question link is: https://leetcode.com/problems/delete-node-in-a-bst/description/).
I wrote the following code:
// Example program
#include <iostream>
#include <string>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* findSmallest(TreeNode* root) {
if(!root) return NULL;
TreeNode* prev=root;
while(root->left) {
cout<<"Visiting: "<<root->val<<"\n";
prev=root;
root=root->left;
}
prev->left=NULL;
cout<<"Returning: "<<root->val<<" and prev was: "<<prev->val<<"\n";
return root;
}
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return NULL;
if(root->val == key) {
//This is the node to be deleted
TreeNode* smallestOnRight = findSmallest(root->right);
//the lines below do not actually change the root node - why?
if(smallestOnRight) smallestOnRight->left=root->left;
if(smallestOnRight) smallestOnRight->right=root->right;
root=smallestOnRight;
return root;
}
if(root->val>key)
deleteNode(root->left, key);
if(root->val<key)
deleteNode(root->right, key);
return root;
}
int main()
{
TreeNode* root = new TreeNode(8);
root->left = new TreeNode(3);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(6);
root->left->right->left = new TreeNode(4);
root->left->right->right = new TreeNode(7);
root->right = new TreeNode(10);
root->right->right = new TreeNode(14);
root->right->right->left = new TreeNode(13);
deleteNode(root, 3);
}
I am wondering why the lines below the comment do not actually change the root node. So, if the original tree was like (a), then after this process, the new tree is like (b), whereas it should have been like (c):
(a): Image (a)
(b): Image (b)
(c): Image (c)
So, basically only the node3 should be replaced with node4, but unfortunately this does not happen. Why is this so?
Edit: So the input would be:
[8,3,10,1,6,null,14,null,null,4,7,13,null]
3
(Tree is traversed in level order).
Edit: Here is the cpp.sh link: http://cpp.sh/9h2z
You have not preserved node8 that should have been modified to point to node4. You need to preserve the parent of the node that is being deleted and modify the linkage in there.

DFS in C++: return node if it contains searched key

My program goal is to search for a tree node with a given key using depth-first search and if a node with that key is found it will be returned to the caller function. The problem is that accessing the node after DFS execution terminates the program with a segmentation fault, exactly when it searches for a node in the right subtree, but not when searching on the left subtree.
This is the source code:
#include <iostream>
using namespace std;
struct node
char data;
struct node *left;
struct node *right;
};
struct node *root = nullptr;
struct node* addNewNode(char newData) {
struct node* newNode = new node;
newNode->data = newData;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
struct node* preOrder(struct node *srcNode, char key) {
if (srcNode != nullptr) {
if (srcNode->data == key)
return srcNode;
return preOrder(srcNode->left, key);
return preOrder(srcNode->right, key);
}
}
int main() {
root = addNewNode('a');
root->left = addNewNode('e');
root->right = addNewNode('c');
root->left->left = addNewNode('h');
root->left->right = addNewNode('z');
struct node* res = preOrder(root, 'c');
cout << res->data;
return 0;
}
Your preOrder function does not always return a value. If srcNode is nullptr you should return nullptr.
Your compiler should be warning you about this! If it is not, then change your compiler settings, or get a better compiler.
Edit: Also - you should check that res is not nullptr before you try to use it.
Edit2: Didn't see this bit
return preOrder(srcNode->left, key);
return preOrder(srcNode->right, key);
The second call to preOrder will never be called (because you have already returned), so you are never searching right hand nodes. You need to change the logic so it search on the right hand node if the left search returned nullptr.

Identifier not found

So for my assignment, I am supposed to implement a Node class that just contains data and pointers to its two siblings and a BinaryTree that reads in these Nodes and creates a binary tree out of them. My problem is pointing to the root of the Tree does not seem to work. Any help you can provide would be appreciated!
Note: The error is found a few lines into the addNode method in the BinaryTree.cpp file which can be found at the end of the question. Also, I am not able to access the value of size either, so I believe this is some sort of weird scope issues I cannot resolve. I also cannot use the "this" keyword in the addNode function.
I am also not allowed to use structs, per my homeworks' instruction.
Node.H
#include <iomanip>
using namespace std;
class Node
{
public:
int data;
Node* leftChild;
Node* rightChild;
Node(int data, Node* leftChild, Node* rightChild);
};
Node.cpp
#include <iomanip>
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node(int data, Node* leftChild, Node* rightChild)
{
this->data = data;
this->leftChild = leftChild;
this->rightChild = rightChild;
}
BinaryTree.H
#include <iomanip>
#include "Node.h"
using namespace std;
class Tree
{
public:
Tree(int data);
void addNode(int data);
void inOrder(Node* N);
protected:
Node* root;
int size;
int data;
private:
int printNode(Node* N);
};
BinaryTree.cpp
#include <iostream>
#include <iomanip>
#include "BinaryTree.h"
using namespace std;
//Tree constructor. Sets the values of data, size, and root.
Tree::Tree(int data)
{
this->data = data;
this->size = 0;
this->root = new Node(data, NULL, NULL);
}
//Adds a node to the current Tree.
void addNode(int data)
{
Node* tempNode = new Node(data, NULL, NULL);
Node* current = root; //THIS IS THE ERROR LINE.
while(current!=NULL)
{
//If the data we are trying to add is already in the Tree
if(current->data == tempNode->data)
{
cout << "Data already in the Tree.";
}
//If the data for the new node is larger than the old
else if(current->data < tempNode->data)
{
//See if the right child is null. If so, add the tree node there.
if(current->rightChild == NULL)
{
current->rightChild = tempNode;
return;
}
//Otherwise, traverse down the right tree.
else
{
current = current->rightChild;
}
}
//The data is smaller than the current node
else
{
//See if the left child is null. If so, add the tree node there.
if(current->leftChild == NULL)
{
current->leftChild = tempNode;
return;
}
//Otherwise, traverse down the left tree
else
{
current = current->leftChild;
}
}//End of leftChild Else
}//End of while
}//End of addNode
void addNode(int data)
should be:
void Tree::addNode(int data)
as it is a member function of class Tree
//Adds a node to the current Tree.
void addNode(int data)
Should be:
//Adds a node to the this Tree
void Tree::addNode(int data)