is this binary tree function postorder or preorder? - c++

My understanding is that in binary tree, the preorder traversal visits the root node first, then traverses the left subtree, and finally traverses the right subtree. The postorder traversal visits the left subtree, then the right subtree, and finally the root node.
In the final of my class this asks if this the function f() is preorder or postorder.
template
int f(treeNode* t)
{
int n=0, leftValue, rightValue;
if (t != NULL) {
if (t->leftChild != NULL || t->rightChild != NULL)
n++;
leftValue = f(t->leftChild);
rightValue = f(t->rightChild);
return n + leftValue + rightValue;
} else
return 0;
}
Doesn't this travel the down the left tree, the the right tree before processing anything? So it should be postorder shouldn't it?
Similar to how this function to delete the nodes in a binary tree:
clear(Node* curr) {
if (!curr)
return;
clear(curr->left);
clear(curr->right);
delete curr;
}

Related

Pre-order tree traversal and the order of stack pushing

Does the order of stack pushing matter in pre-order traversal of trees?
For example, Iterative Preorder Traversal
In the following source code,
void iterativePreorder(node* root)
{
if (root == NULL)
return;
stack<node*> nodeStack;
nodeStack.push(root);
while (nodeStack.empty() == false)
{
struct node* node = nodeStack.top();
printf("%d ", node->data);
nodeStack.pop();
if (node->right)//<--------------------------------
nodeStack.push(node->right);
if (node->left)//<---------------------------------
nodeStack.push(node->left);
}
}
if I switch the position of stack-pushing of left and right nodes,
void iterativePreorder(node* root)
{
if (root == NULL)
return;
stack<node*> nodeStack;
nodeStack.push(root);
while (nodeStack.empty() == false)
{
struct node* node = nodeStack.top();
printf("%d ", node->data);
nodeStack.pop();
if (node->left)//<---------------------------------
nodeStack.push(node->left);
if (node->right)//<--------------------------------
nodeStack.push(node->right);
}
}
does it make any difference?
I mean, if the positions are switched, is that still a proper pre-order traversal?

C++ Segmentation fault -- Self-balancing Tree insertion

I'm trying to solve a self-balancing tree problem on Hackerrank (https://www.hackerrank.com/challenges/self-balancing-tree/problem) and I keep getting a Segmentation fault in the last 3 test cases. I saw that this same problem had been posted before and tried to apply the same approach (check for nullptr) to my case, but no success so far. The following code is written in C++ and I would appreciate a lot if you guys could help me out. Thanks!
/* Node is defined as :
typedef struct node
{
int val;
struct node* left;
struct node* right;
int ht;
} node; */
node * newNode(int val)
{
node * newNode = new node;
newNode->val = val;
newNode->left = nullptr;
newNode->right = nullptr;
newNode->ht = 0;
return newNode;
}
int getHeight(node* root)
{
if(root == nullptr) {
return -1;
} else {
return root->ht;
}
}
node* rightRotate(node* root)
{
node* temp = root->left;
root->left = temp->right;
temp->right = root;
root->ht = 1 + max(getHeight(root->left), getHeight(root->right));
temp->ht = 1 + max(getHeight(temp->left), getHeight(temp->right));
return temp;
}
node* leftRotate(node* root)
{
node* temp = root->right;
root->right = temp->left;
temp->left = root;
root->ht = 1 + max(getHeight(root->left), getHeight(root->right));
temp->ht = 1 + max(getHeight(temp->left), getHeight(temp->right));
return temp;
}
node * insert(node * root,int val)
{
if(root == nullptr) {
root = newNode(val);
return root;
}
if(val > root->val) {
root->right = insert(root->right, val);
}
else if(val < root->val) {
root->left = insert(root->left, val);
}
else{ return 0; }
root->ht = 1 + max(getHeight(root->left),getHeight(root->right));
int balance = getHeight(root->left) - getHeight(root->right);
if(root->left != nullptr && balance > 1) {//Left subtree disbalanced
if(val < root->left->val) {
//Left-Left case: perform a right rotation on the disb. node
return rightRotate(root);
}
else {
//Left-Right case: perfom a left rotation on the disb. node left subtree
//and a right rotation on the disb. node
root->left = leftRotate(root->left);
return rightRotate(root);
}
}
if(root->right != nullptr && balance < -1) {//Right subtree disbalanced
if(val > root->right->val) {
//Right-Right case: perform a left rotation on the disb. node
return leftRotate(root);
}
else {
//Right-Left case: perfom a right rotation on the disb. node right subtree
//and a left rotation on the disb. node
root->right = rightRotate(root->left);
return leftRotate(root);
}
}
return root;
}
Edit:
For debugging purposes I've used an online gdb and added to the code above the following traversal method and main function:
void inOrder(node* root) {
if(root == NULL) {
return;
} else {
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
}
int main()
{
node* root=NULL;
root=insert(root,2);
root=insert(root,4);
root=insert(root,3);
inOrder(root);
return 0;
}
After trying to insert the values 2, 4 and 3, in this order, we would have a disbalanced tree since the right subtree would have a height of 1 while the left subtree would have a height of -1 (leaf node is nullptr) and the balance factor would be less than -1. Further analysis shows that we have a RIGHT-LEFT case since the node causing the disbalance is the left child of the right child of the disbalanced node (root 2). We would then have to perform a right rotation on the disbalanced node right child followed by a left rotation on the disbalanced node itself, and the tree should end up looking like the following:
3
/ \
2 4
Thanks to everyone who tried helping me out on this one, it turns out there is no limit to how dumb I can be. I believe I've figured out what I had done wrong.
The problem in this question lies on the section that checks if the right subtree is disbalanced and, if so, performs the necessary rotations. On the code piece below, it should be
root->right = rightRotate(root->right);
instead of
root->right = rightRotate(root->left);

Error in finding lowest common ancestor in tree

I am trying to find the lowest common ancestor of the two given values in the tree.
My approach is to traverse to the bottom left of the tree and check individual nodes weather they have both the nodes under them. The first node to give a match is the lowest common ancestor.
Can anyone tell me the error in this function.
/*
Node is defined as
typedef struct node
{
int data;
node * left;
node * right;
}node;
*/
bool find(node *root,int val) //to check if the value exist under the given node or not
{
if(root==NULL)
return false;
if(root->data==val)
return true;
if((root->left&&find(root->left,val))||(root->right&&find(root->right,val)))
return true;
return false;
}
node * lca(node * root, int v1,int v2) //to find the lowest common ancestor
{
if(root==NULL)
return NULL;
static node* ans=NULL;
lca(root->left,v1,v2); //traversing to the bottom of the tree
lca(root->right,v1,v2);
if((find(root->left,v1)&&find(root->right,v2))||(find(root->left,v2)&&find(root->right,v1))) //checking the existence of both nodes under the tree
{
if(ans==NULL)
ans=root;
}
return ans; //returning the lca
}
Your recursive function should return only a node if the result was found. It should return NULL if the result node was not found. Break if the node was found, else continue. I would do it like this:
node * lca(node * root, int v1,int v2) //to find the lowest common ancestor
{
if(root==NULL)
return NULL;
node* ans=NULL;
// search the left child tree
ans = lca(root->left,v1,v2);
if (ans != NULL)
return ans; // if you found it you are finished
// search the right child tree
ans = lca(root->right,v1,v2);
if (ans != NULL)
return ans; // if you found it you are finished
// test this tree node
if( (find(root->left,v1)&&find(root->right,v2)) ||
(find(root->left,v2)&&find(root->right,v1)))
{
// If the condition is true, this node is the result
return root;
}
return NULL; // Neither this node nor any subordinate node of this node is the result
}

Binary Tree - Print Left branches only - Using PostOrder Traverse - C++

Hi!
I would like to know what can be the if statement's condition so all left branches of a binary tree could be printed using postorder traverse.
template <class dataType>
void PrintLeft (BinaryTree <dataType> * bt) {
if (!(bt == NULL))
{
//traverse left child
PrintLeft (bt->left());
//traverse right child
PrintLeft (bt->right());
//visit tree
if(/*no idea what goes here*/)
cout << bt->getData() <<"\t";
}
}
I understand that you want to visit only the nodes that were seen from a left branch. Since it is postorder, you must visit them when you get back on the right branch. So, such as said by πάντα ῥεῖ, you can use a boolean flag indicating from which type of branch you have discovered the node.
So a possible way would be as follows:
using Node = BinaryTree <int>; // or another type supporting << operator
void printLeft(Node * root, bool from_left)
{
if (root == nullptr) // empty tree?
return;
printLeft(root->left, true); // this node must be visited in postorder
printLeft(root->right, false); // this one must not be visited in postorder
if (from_left) // was root seen from a left arc?
cout << root->getData() << "\t"; // visit only if was seen from a left branch
}
There is an ambiguity with the root. I assume that it must not be printed because it is not reached from a left branch (nor right too).
So the first call should be:
printLeft(root, false);
Just as verification, for this tree:
The algorithm produces as left postorder traversal the following sequence
0 1 4 3 8 9 12 11 16 18
here goes code for postorder traversing
void postorder(BinaryTree *bt)
{
if(bt!=NULL)
{
postorder(t->lp);
postorder(t->rp);
//No Code Goes Here
cout<<bt->data<<"\t";
}
}
Try This One
void leftViewUtil(struct node *root, int level, int *max_level)
{
// Base Case
if (root==NULL) return;
// If this is the first node of its level
if (*max_level < level)
{
printf("%d\t", root->data);
*max_level = level;
}
// Recur for left and right subtrees
leftViewUtil(root->left, level+1, max_level);
leftViewUtil(root->right, level+1, max_level);
}
// A wrapper over leftViewUtil()
void leftView(struct node *root)
{
int max_level = 0;
leftViewUtil(root, 1, &max_level);
}
// Driver Program to test above functions
int main()
{
struct node *root = newNode(12);
root->left = newNode(10);
root->right = newNode(30);
root->right->left = newNode(25);
root->right->right = newNode(40);
leftView(root);
return 0;
}
if(!bt->left()==NULL)
cout << bt->left()->getData() << "\t";

how to delete a Node in binary tree [duplicate]

This question already has answers here:
deletion in a binary search tree
(2 answers)
Closed 4 years ago.
The program is simple do the following step:
find min value of a binary tree;
record the min value in a vector;
delete the node with min value in the tree;
repeat 1-3 till the tree is empty.
No error is reported when run, but function removeNode is keep printf("Remove bug1!\n"); I can not find any logical mistake, so I do not understand why this happens. The structure of this function is:
'if min=key`,found it,call function removeRootMatch
else if min<root->key and 'left is not NULL`,go left
else print bug
The tree is defined as following, language is c++
typedef struct myNode* LPNode;
typedef struct myNode Node;
struct myNode
{
double key;
LPNode Left; //left subtree
LPNode Right; //right subtree
};
Main part of program is as following:
nmax is initialed as 0,
sortedvector is alloacted a vector with space as large as the total nodes in the tree,
min is initialed as 99999.
minValue will return the min value of tree.
compareDouble(a,b) will return 1 if a < b,return 2 if a > b,return 3 if equal
//remove root
void removeRootMatch(LPNode Root)
{
LPNode tmp = MakeNewNode(Root->key);
tmp->Left = Root->Left;
tmp->Right = Root->Right;
//no child
if(Root->Left==NULL && Root->Right == NULL) {
Root = NULL;
delete Root;
} else if(Root->Left==NULL && Root->Right!=NULL){ //one right child
Root = Root->Right;
tmp->Right = NULL;
delete tmp;
} else {
printf("Remove root bug!\n");
}
}
//remove a node
void removeMatch(LPNode Root,LPNode match,bool left)
{
//no child
if(match->Left==NULL && match->Right == NULL){
left==true?
Root->Left=NULL:
Root->Right=NULL;
delete match;
}
else if(match->Left==NULL && match->Right!=NULL){//one right child
left==true?
Root->Left=match->Right:
Root->Right=match->Right;
delete match;
} else {
printf("Remove root bug!\n");
}
}
//delete a node
void removeNode(LPNode Root,double min)
{
if(compareDouble(min,Root->key)==3){
removeRootMatch(Root);
}else if(compareDouble(min,Root->key)==1 && Root->Left != NULL) {
compareDouble(min,Root->key)==3 ?
removeMatch(Root,Root->Left,true):
removeNode(Root->Left,min);
}else{
printf("Remove bug1!\n");
}
}
This is the function call removeNode function.
//call minValue to find the min key
//record the min key in a vector
//call removeNode to delete the Node
//repeat till the tree is empty
void problem1(LPNode Root,double* sortedvector,int& nmax)
{
double min = MAX;
while(Root!=NULL)
{
sortedvector[nmax] = minValue(Root,min) ;
nmax++;
removeNode(Root,min);
}
printf("The tree is empty");
}
sortedvector[nmax] = minValue(Root,min) ;
removeNode(Root,sortedvector[nmax]);//change here
nmax++;
you have problem to pass the min. I am here to answer, not just read the title and vote.