I am building a binary tree. The binary tree is pre-built in a file and I need to construct it. Due to the way it is structured, I read the tree into an array. Each tree nodes look something like this.
struct Tree_Node
{
float normalX;
float normalY;
float normalZ;
float splitdistance;
long region;
long left, right; //array index
Tree_Node* left_node; // pointer to left node
Tree_Node* right_node; // pointer to right node
} typedef Tree_Node;
I have tried a number of ways to write some code that will build the tree. Let me give you some pseudocode so you understand what I am trying to do.
Read in head node. Node is number one in the array.
If the node has a right and left array index, create new nodes and
insert the information from the array
indicies into that tree node.
If the node does not have a right and left index, it is a leaf node.
Here is my building function:
void WLD::treeInsert(BSP_Node *tree_root, int node_number)
{
/// Add the item to the binary sort tree to which the parameter
// "root" refers. Note that root is passed by reference since
// its value can change in the case where the tree is empty.
if ( tree_root == NULL )
{
// The tree is empty. Set root to point to a new node containing
// the new item. This becomes the only node in the tree.
tree_root = new BSP_Node();
tree_root->normalX = bsp_array[node_number].normal[0];
tree_root->normalY = bsp_array[node_number].normal[1];
tree_root->normalZ = bsp_array[node_number].normal[2];
tree_root->splitdistance = bsp_array[node_number].splitdistance;;
tree_root->region = bsp_array[node_number].region;
tree_root->left = bsp_array[node_number].left;
tree_root->right = bsp_array[node_number].right;
tree_root->left_node[node_number];
tree_root->right_node[node_number];
errorLog.OutputSuccess("Inserting new root node: %i", node_number);
// NOTE: The left and right subtrees of root
// are automatically set to NULL by the constructor.
// This is important...
}
if ( tree_root->left != 0 )
{
errorLog.OutputSuccess("Inserting left node number: %i!", tree_root->left);
treeInsert( tree_root->left_node, tree_root->left );
}
else if ( tree_root->right != 0 )
{
errorLog.OutputSuccess("Inserting right node: %i!", tree_root->right);
treeInsert( tree_root->right_node, tree_root->right );
}
else if ( tree_root->right == 0 && tree_root->left == 0)
{
errorLog.OutputSuccess("Reached a leaf node!");
return;
}
else
{
errorLog.OutputError("Unknown BSP tree error!");
}
}
My debug shows that the function tries to insert node 2 until the program crashes.
Can someone help me with this?
tree_root->left_node[node_number];
I don't see any code that initializes this array, so this'll be referring to something invalid.
Then by the time you come around to the next function
treeInsert( tree_root->left_node, tree_root->left );
treeInsert will be called with an invalid pointer, since left_node doesn't go anywhere.
I imagine you need something like tree_root->left_node = NULL instead of tree_root->left_node[node_number] so that the recursive call to treeInsert creates the next node.
Related
recently I passed a programming interview where I had to create a method that returns the address of a node (belonging to a tree). The method takes an integer value as an argument.
My code worked on a small tree, but when searching a large tree (300,000 nodes) I got an error stating "cannot access address '0x.....'".
What should I do to fix this?
'''
struct Node
{
int value;
Node* left = nullptr;
Node* right = nullptr;
Node* find_node(int);
};
Node* Node::find_node(int v)// The function is working on small trees only
{
if(this->value == v) //comparing the the value inside the root with the function's argument
return this;
else if(this->value > v) //if v is smaller than the node's value, search the next left node
{
if(this->left == nullptr) //checking if the next node on the left exists
return nullptr; //null returned if there is no more nodes
else
return (this->left)->find_node(v); //Call the find_node function recursively on the left node
}
else if(this->value < v) //if v is bigger than the node's value, search the next right node
{
if(this->right == nullptr) //checking if the next node on the left exists
return nullptr; //null returned if there is no more nodes
else
return (this->right)->find_node(v);// Call the find_node function recursively on the right node
}
return nullptr;// If the value is not found
}
'''
Your code needs lots of activation records on the call stack for repetitive calls to find_node(v). And it may lead to overflow of the call stack.
To avoid it, you can use non-recursive versions of binary search that uses a loop instead. For more information, check this link.
I'm trying to make complete tree from scratch in C++:
1st node = root
2nd node = root->left
3rd node = root->right
4th node = root->left->left
5th node = root->left->right
6th node = root->right->left
7th node = root->right->right
where the tree would look something like this:
NODE
/ \
NODE NODE
/ \ / \
NODE NODE NODE NODE
/
NEXT NODE HERE
How would I go about detecting where the next node would go so that I can just use one function to add new nodes? For instance, the 8th node would be placed at root->left->left->left
The goal is to fit 100 nodes into the tree with a simple for loop with insert(Node *newnode) in it rather than doing one at a time. It would turn into something ugly like:
100th node = root->right->left->left->right->left->left
Use a queue data structure to accomplish building a complete binary tree. STL provides std::queue.
Example code, where the function would be used in a loop as you request. I assume that the queue is already created (i.e. memory is allocated for it):
// Pass double pointer for root, to preserve changes
void insert(struct node **root, int data, std::queue<node*>& q)
{
// New 'data' node
struct node *tmp = createNode(data);
// Empty tree, initialize it with 'tmp'
if (!*root)
*root = tmp;
else
{
// Get the front node of the queue.
struct node* front = q.front();
// If the left child of this front node doesn’t exist, set the
// left child as the new node.
if (!front->left)
front->left = tmp;
// If the right child of this front node doesn’t exist, set the
// right child as the new node.
else if (!front->right)
front->right = tmp;
// If the front node has both the left child and right child, pop it.
if (front && front->left && front->right)
q.pop();
}
// Enqueue() the new node for later insertions
q.push(tmp);
}
Suppose root is node#1, root's children are node#2 and node#3, and so on. Then the path to node#k can be found with the following algorithm:
Represent k as a binary value, k = { k_{n-1}, ..., k_0 }, where each k_i is 1 bit, i = {n-1} ... 0.
It takes n-1 steps to move from root to node#k, directed by the values of k_{n-2}, ..., k_0, where
if k_i = 0 then go left
if k_i = 1 then go right
For example, to insert node#11 (binary 1011) in a complete tree, you would insert it as root->left->right->right (as directed by 011 of the binary 1011).
Using the algorithm above, it should be straightforward to write a function that, given any k, insert node#k in a complete tree to the right location. The nodes don't even need to be inserted in-order as long as new nodes are detected created properly (i.e. as the correct left or right children, respectively).
Assuming tree is always complete we may use next recursion. It does not gives best perfomance, but it is easy to understand
Node* root;
Node*& getPtr(int index){
if(index==0){
return root;
}
if(index%2==1){
return (getPtr( (index-1)/2))->left;
}
else{
return (getPtr( (index-2)/2))->right;
}
}
and then you use it like
for(int i = 0; i<100; ++i){
getPtr(i) = new Node( generatevalue(i) );
}
private Node addRecursive(*Node current, int value) {
if (current == null) {
return new Node(value);
}
if (value < current.value) {
current->left = addRecursive(current->left, value);
} else if (value > current->value) {
current->right = addRecursive(current->right, value);
} else {
// value already exists
return current;
}
return current;
}
I do not know that if your Nodes has got a value instance but:
With this code you can have a sorted binary tree by starting from the root.
if the new node’s value is lower than the current node’s, we go to the left child. If the new node’s value is greater than the current node’s, we go to the right child. When the current node is null, we’ve reached a leaf node and we can insert the new node in that position.
I've created Raw BinaryTree. In this tree, insertion is not like BST, its like this::
If tree is empty then add value & make it root. (suppose 30)
If tree is not empty then input father value (30) & add new value (20) to its left subtree.
If left subtree is not empty then, insert value (20) to right subtree.
For next insertion, again take father value to determine where value is to be added.
& so on..
Its working fine except when I try to delete a node with two children. Method Im using to delete is deleteWithCopy.
As my instructor has told, deletewithcopy is:
1. Find father of node (temp) which is to be deleted.
2. If temp (node to be deleted) is the right child of 'father' then find temp's immediate Successor
3. If temp (node to be deleted) is the left child of 'father' then find temp's immediate Predecessor
4. Swap value of temp with its predecessor/succesor
5. Delete temp (which is now leaf of tree).
NOW How to find Successor & Predecessor.
Successor = logical successor of a node is its right-most child in left subtree
Predecessor = logical predecessor of a node is its left-most child in right subtree
According to algorithm I have created the function, but after deleting, when I traverse (or print) the tree, it shows run time error,
Unhandled exception at 0x008B5853 in binarytree.exe: 0xC0000005: Access violation reading location 0xFEEEFEEE.
which is error for "0xFEEEFEEE is used to mark freed memory in Visual C++."
I have dry run-ed this thing again & again, there is nothing out of bounds in memory that Im trying to acces, I have fixed every loose end, but still :(
Here is the function:
void BinaryTree<mytype>::deletewithTwoChild(BTNode<mytype> *temp)
{
BTNode<mytype> *father = findfather(temp, root); //found address of father of temp node & stored it in pointer
BTNode<mytype> *leaf = temp; //created a copy of temp node
/////CASE 1 (for predecessor)
if(temp==root || father->left==temp) //if temp is left child of its father then
{
leaf = leaf->left; //move leaf 1 time left
while(leaf->right!=0 ) //until leaf reaches the right most node of left subtree
{
leaf = leaf->right; //move leaf 1 time to right
}
//swapping values
mytype var = leaf->key_value; //created a template variable to store leaf's key
leaf->key_value = temp->key_value; //assigning temp's key to leaf
temp->key_value = var; //assigning leaf's key to temp
if(leaf->right!=0) //if leaf has right child then call deletewithOneChild function
{
deletewithOneChild(leaf); //call to respective function
}
else if(leaf->left==0 && leaf->right==0) //if leaf has no children then
{
deleteWithNoChild(leaf); //call to respective function
}
}
/////CASE 2 (for successor)
else if(father->right==temp) //if temp is right child of its father, then
{
leaf = leaf->right; //move leaf 1 time right
while(leaf->left!=0) //until leaf reaches the last node of tree which has no child
{
leaf = leaf->left; //move leaf 1 time to left
}
//swapping values
mytype var = leaf->key_value; //created a template variable to store leaf's key
leaf->key_value = temp->key_value; //assigning temp's key to leaf
temp->key_value = var; //assigning leaf's key to temp
if(leaf->right!=0) //if leaf has right child then call deletewithOneChild function
{
deletewithOneChild(leaf); //call to respective function
}
else if(leaf->left==0 && leaf->right==0) //if leaf has no children then
{
deleteWithNoChild(leaf); //call to respective function
}
}
}
Data Set I m using:
30
/ \
20 80
/ / \
10 40 120
\ / \
60 100 140
/ \ / \
50 70 130 150
Im trying to delete node 80, 60, 120, 140 when the run time error pops up. Plz help :(( Also I need guidence how to handle tree iff 30 is deleted.
As I know, the definition of successor and predecessor are different.
Successor : the minimum node of right subtree, that is, the left-most node of right subtree.
Predecessor : the maximum node of left subtree, that is, the right-most node of left subtree.
Back to Issue 1. I have noticed the if-else condition after swapping values in case 1. Since, in case 1, you are finding the right most node of the subtree, leaf->right always be null and leaf->left may not be null. As a result, none of the delete function be called in case after swapping values. This will cause the issue of wrong BST or even worse, the crash of the program. Therefore, the if-else condition in case would be:
// leaf->right always be null, only need to verify leaf->left.
if (leaf->left != 0)
{
deleteWithOneNode(leaf);
}
else
{
deleteWithNoChild(leaf);
}
Issue 2. As I know, the remove of one node in BST has no rule to choose predecessor or successor and the parent(father) node of the removed node is used only when swapping the whole node rather then swapping the value of the node only. Therefore, my delete function would be:
void BinaryTree<myType>::delete(BTNode<myType>* node, BTNode<myType>* parent)
{
if (node->right) // find successor first
{
BTNode* ptrParent = node;
BTNode* ptr = node->right;
while (ptr->left)
{
ptrParnet = ptr;
ptr = ptr->left;
}
// Since the ptr will be delete, we only assign the value of ptr to the value node
node->key_value = ptr->key_value;
if (node == ptrParent)
{
ptrParnet->right = ptr->right;
}
else
{
ptrParent->left = ptr->right;
}
delete ptr;
}
else if (node->left) // find predecessor
{
BTNode* ptrParent = node;
BTNode* ptr = node->left;
while (ptr->right)
{
ptrParent = ptr;
ptr = ptr->right;
}
// Since the ptr will be delete, we only assign the value of ptr to the value node
node->key_value = ptr->key_value;
if (node == ptrParent)
{
ptrParent->left = ptr->left;
}
else
{
ptrParent->right = ptr->left;
}
delete ptr;
}
else
{
if (node->key_value > parent->key_value)
{
parent->right = NULL;
}
else
{
parent->left = NULL;
}
delete node;
}
}
By using the function, the tree after removing 30 would be
40
/ \
20 80
/ / \
10 60 120
/ \ / \
50 70 100 140
/ \
130 150
This my my successor func:
int
BalancedTree::successor( TreeNode *node ) // successor is the left-most child of its right subtree,
{
TreeNode *tmp = node;
int successorVal = -1;
tmp = tmp->m_RChild;
if( NULL != tmp )
{
while( NULL != tmp->m_LChild )
tmp = tmp->m_LChild;
// now at left most child of right subtree
successorVal = tmp->m_nodeData;
}
return successorVal;
} // successor()
my instructor gave us a file filled with random data. I place all this data into the tree, the insert method works, but once the remove method starts, the successor function at some point returns the same value of the the node I'm looking for a successor for. This shouldn't be able to happen correct? is my successor function correct? If you want to see the remove method just mention it.
Your definition of successor is flawed already: if the node doesn't have a right node the successor is one of its ancestors: the first one whose left child is the node or one of its ancestors. Only if no such ancestor exists there is mo successor. Personally I would return an iterator to the node but otherwise the code seems to be OK.
I have a binary tree data structure of:
//Declare Data Structure
struct CP {
int id; //ID of the Node
int data; //Data of the Node
CP * left; //Pointer to the Left Subtree
CP * right; //Pointer to the Right Subtree
};
typedef CP * CPPtr;
Without changing the tree structure, how do I actually calculate the depth if given a node id. (id is a unique indicator to each tree node)
your code is lack of some base steps or necessary initializations.
BTree_Helper(BTree *Tree){// this is roughly written like pseudo code
if(TLeft == NULL && TRight == NULL){
depth of tree = 0 ;
}
else if (TLeft == NULL){
depth of tree = depth of right tree ;
}
else if(TRight==NULL){
depth of tree = depth of left tree;
}
else{
depth of tree = the maximum between depth of left and depth of right;
}
}
I just gave some hints for your convinence.
Think carefully and try as many test suites as possible.
Going off of what y26jin suggested, maybe something like this?
BTree_Helper(CP *TreeNode) {
CP *TLeft = TreeNode->left;
CP *TRight = TreeNode->right;
if(TLeft == NULL && TRight == NULL){
return 0;
}
else if (TLeft == NULL){
return 1+(BTree_Helper(TRight));
}
else if(TRight==NULL){
return 1+(BTree_Helper(TLeft));
}
else{
return 1+max(BTree_Helper(TLeft),BTree_Helper(TRight));
}
}
I can't actually test the code right now, sorry if I'm way off here. But I think something along these lines should work.
I'm going to assume that id is the search key for the tree. In other words, the id of any node on the left subtree is less than the id of this node, and the id of any node on the right subtree is greater than the id of this node. Also, id is assumed to be unique.
To find a node with a given ID, given a pointer to the root node of the tree, you just do:
CP* find(CP* root, int searchID)
{
// Starting point.
CP* node = root;
while(node)
{
// Search hit?
if(node->id == searchID)
return node;
// Turn left or right?
if(node->id < searchID)
node = node->left;
else
node = node->right;
}
return 0; // No node with the given ID found.
}
Finding depth is a simple modification of this function: instead of returning a node, you keep count of how many levels you descend. A depth of 0 means the root node is what you want; a depth of 1 means either the left or right nodes; a depth of 2 means any of their direct children, etc. So it's really how many times you have to loop:
int depth(CP* root, int searchID)
{
// Starting point.
CP* node = root;
int depth = 0;
while(node)
{
// Search hit?
if(node->id == searchID)
return depth;
// Descending a level...
++depth;
// Turn left or right?
if(node->id < searchID)
node = node->left;
else
node = node->right;
}
return -1; // No node with the given ID found.
}
Note the special value -1 for "not found".
I recommend storing the depth of a node's subtree in that node. Then you can just update the depth of the tree as you add nodes to it. Whenever you add a node, back out of the tree, updating the depth of each node along the path to the root on the way out. If at any point, the new depth of a node's modified subtree is not greater than the depth of the node's other subtree, you can short-circuit.
The benefits to this approach are:
It's worst-case performance is O(log n) (assuming that the tree is balanced).
It is extremely easy to write non-recursively
Read about basic tree/graph search algorithms: breadth-first search (BFS) and depth-first search (DFS). Try implementing DFS both recursively and with an explicit stack<T>. Implement BFS using a queue<T>.
Pay attention to the efficiency of your approach. If you want to look-up the depth of nodes repeatedly it will probably be much faster to store the depth of every node in the tree in some sort of look-up table. Ideally a hash table but a map<T1, T2> will do in most cases.
You'll learn a lot from the above exercises. Good luck!
You can calculate the depth from any node using recursion:
int countChildren(CPPtr node) {
if ( node != null )
return 1 + countChildren(node->left) + countChildren(node->right);
else
return 0;
}
You have to pass pointers to lDepth and rDepth, not the values themselves, like so:
nodeDepth_Helper(tree,id, &lDepth, &rDepth);
Furthermore, I think the arguments to nodeDepth_helper should be declared as pointers to ints:
void nodeDepth_Helper(CPPtr tree, int id, int* lDepth,int* rDepth)
making these changes throughout should fix your problem.