Binary Trees Implementation
Binary Trees Implementation
struct node
{
int data;
struct node *left;
struct node *right;
};
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
/*create root*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
getchar();
return 0;
}
Tree traversals:
2. Inorder Traversal
void printInorder(struct node* node)
{
if (node == NULL)
return;
4. Postorder traversal
void printPostorder(struct node* node)
{
if (node == NULL)
return;
while (temp_node)
{
printf("%d ", temp_node->data);
6. Level order traversal (Method 2): uses function which prints nodes
at a given level
void printLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
{
printGivenLevel(root, i);
printf("\n");
}
}
Do something like normal level order traversal order. Following are the differences with normal
level order traversal
1) Instead of printing a node, we push the node to stack
2) Right subtree is visited before left subtree
// Now pop all items from stack one by one and print them
while (S.empty() == false)
{
root = S.top();
cout << root->data << " ";
S.pop();
}
}
*Try to use STL wherever possible
10. Preorder without recursion
void iterativePreorder(node *root)
{
// Base Case
if (root == NULL)
return;
/* Pop all items one by one. Do following for every popped item
a) print it
b) push its right child
c) push its left child
Note that right child is pushed first so that left is processed first */
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left);
}
}
*similarly look for inorder and postorder without recursion
11. Lowest Common Ancestor between two nodes
Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as
the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a
descendant of itself).
// This function returns pointer to LCA of two given values n1 and n2.
// This function assumes that n1 and n2 are present in Binary Tree
/*If either n1 or n2 matches with root's key, report the presence by returning root (Note that if a key is ancestor of
other, then the ancestor key becomes LCA */
/* If both of the above calls return Non-NULL, then one key is present in once subtree and other is present in
other, So this node is the LCA */
if (root->data == target)
return true;
/* If target is present in either left or right subtree of this node, then print this node */