0% found this document useful (0 votes)
57 views10 pages

Level Order Traversal of Binary Tree - Techie Delight

The document contains code snippets and explanations for various binary tree traversal and searching algorithms, including: 1) Level order traversal, which prints nodes level by level from top to bottom. 2) Spiral (zigzag) traversal, which alternates between left-to-right and right-to-left printing at each level. 3) Finding the lowest common ancestor (LCA) of two nodes and using it to calculate the distance between nodes. 4) Checking if all leaves are at the same level or finding the deepest leaf at an odd level. 5) Printing the left view or finding the deepest left leaf of the tree. 6) Determining if two nodes are cousins (have the

Uploaded by

akg299
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views10 pages

Level Order Traversal of Binary Tree - Techie Delight

The document contains code snippets and explanations for various binary tree traversal and searching algorithms, including: 1) Level order traversal, which prints nodes level by level from top to bottom. 2) Spiral (zigzag) traversal, which alternates between left-to-right and right-to-left printing at each level. 3) Finding the lowest common ancestor (LCA) of two nodes and using it to calculate the distance between nodes. 4) Checking if all leaves are at the same level or finding the deepest leaf at an odd level. 5) Printing the left view or finding the deepest left leaf of the tree. 6) Determining if two nodes are cousins (have the

Uploaded by

akg299
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Level Order Traversal of Binary Tree - Techie Delight

bool printLevel(Node* root, int level)


{
if (root == nullptr)
return false;

if (level == 1)
{
cout << root->key << " ";

// return true if at-least one node is present at given level


return true;
}

bool left = printLevel(root->left, level - 1);


bool right = printLevel(root->right, level - 1);

return left || right;


}

// Function to print level order traversal of given binary tree


void levelOrderTraversal(Node* root)
{
if (root == nullptr)
return;

// start from level 1 -- till height of the tree


int level = 1;

// run till printLevel() returns false


while (printLevel(root, level))
level++;
}
Spiral Order Traversal of Binary Tree - Techie Delight
bool printLevelLeftToRight(Node* root, int level)
{
if (root == nullptr)
return false;

if (level == 1)
{
cout << root->key << " ";
return true;
}

// process left child before right child


bool left = printLevelLeftToRight(root->left, level - 1);
bool right = printLevelLeftToRight(root->right, level - 1);

return left || right;


}

// Function to print all nodes of a given level from right to left


bool printLevelRightToLeft(Node* root, int level)
{
if (root == nullptr)
return false;

if (level == 1)
{
cout << root->key << " ";
return true;
}

// process right child before left child


bool right = printLevelRightToLeft(root->right, level - 1);
bool left = printLevelRightToLeft(root->left, level - 1);

return right || left;


}

// Function to print level order traversal of given binary tree


void spiralOrderTraversal(Node* root)
{
if (root == nullptr)
return;

// start from level 1 -- till height of the tree


int level = 1;

// run till either function returns false


while (printLevelLeftToRight(root, level++) &&
printLevelRightToLeft(root, level++));
}
Find the distance between given pairs of nodes in a binary tree - Techie Delight
bool isNodePresent(Node* root, Node* node)
{
// base case
if (root == nullptr)
return false;

// if node is found, return true


if (root == node)
return true;

// return true if node is found in the left subtree or right subtree


return isNodePresent(root->left, node) ||
isNodePresent(root->right, node);
}

// Helper function to find level of given node present in binary tree


int findLevel(Node *root, Node* node, int level)
{
// base case
if (root == nullptr)
return INT_MIN;
// return level if node is found
if (root == node)
return level;

// search node in left subtree


int left = findLevel(root->left, node, level + 1);

// if node is found in left subtree, return


if (left != INT_MIN)
return left;

// else continue the search in right subtree


return findLevel(root->right, node, level + 1);
}

// Function to find lowest common ancestor of given nodes x and y where


// both x and y are present in the binary tree.
Node* findLCA(Node* root, Node* x, Node* y)
{
// base case 1: if tree is empty
if (root == nullptr)
return nullptr;

// base case 2: if either x or y is found


if (root == x || root == y)
return root;

// recursively check if x or y exists in the left subtree


Node* left = findLCA(root->left, x, y);

// recursively check if x or y exists in the right subtree


Node* right = findLCA(root->right, x, y);

// if x is found in one subtree and y is found in other subtree,


// update lca to current node
if (left && right)
return root;

// if x and y exists in left subtree


if (left)
return left;

// if x and y exists in right subtree


if (right)
return right;
}

// Function to find the distance between node 'x' and node 'y' in a
// given binary tree rooted at 'root' node
int findDistance(Node *root, Node* x, Node* y)
{
// lca stores lowest common ancestor of x and y
Node *lca = nullptr;

// call LCA procedure only if both x and y are present in the tree
if (isNodePresent(root, y) && isNodePresent(root, x))
lca = findLCA(root, x, y);
else
return INT_MIN;

// return distance of x from lca + distance of y from lca


return findLevel(lca, x, 0) + findLevel(lca, y, 0);

// above return statement is equivalent to


// findLevel(root, x, 0) + findLevel(root, y, 0) -
// 2*findLevel(root, lca, 0);

// we can avoid calling isNodePresent() function by using


// the return values of findLevel() function to check if
// x and y are present in the tree or not
}
Maximum width of a binary tree - GeeksforGeeks
http://www.geeksforgeeks.org/maximum-width-of-a-binary-tree/

int getMaxWidth(struct node* root)


{
int maxWidth = 0;
int width;
int h = height(root);
int i;

/* Get width of each level and compare


the width with maximum width so far */
for(i=1; i<=h; i++)
{
width = getWidth(root, i);
if(width > maxWidth)
maxWidth = width;
}

return maxWidth;
}

/* Get width of a given level */


int getWidth(struct node* root, int level)
{

if(root == NULL)
return 0;

if(level == 1)
return 1;

else if (level > 1)


return getWidth(root->left, level-1) +
getWidth(root->right, level-1);
}

// A function that fills count array with count of nodes at every


// level of given binary tree
void getMaxWidthRecur(struct node *root, int count[], int level);

/* Function to get the maximum width of a binary tree*/


int getMaxWidth(struct node* root)
{
int width;
int h = height(root);

// Create an array that will store count of nodes at each level


int *count = (int *)calloc(sizeof(int), h);

int level = 0;

// Fill the count array using preorder traversal


getMaxWidthRecur(root, count, level);

// Return the maximum value from count array


return getMax(count, h);
}

// A function that fills count array with count of nodes at every


// level of given binary tree
void getMaxWidthRecur(struct node *root, int count[], int level)
{
if(root)
{
count[level]++;
getMaxWidthRecur(root->left, count, level+1);
getMaxWidthRecur(root->right, count, level+1);
}
}

Find depth of the deepest odd level leaf node - GeeksforGeeks


http://www.geeksforgeeks.org/find-depth-of-the-deepest-odd-level-node/
int depthOfOddLeafUtil(Node *root,int level)
{
// Base Case
if (root == NULL)
return 0;

// If this node is a leaf and its level is odd, return its level
if (root->left==NULL && root->right==NULL && level&1)
return level;

// If not leaf, return the maximum value from left and right subtrees
return max(depthOfOddLeafUtil(root->left, level+1),
depthOfOddLeafUtil(root->right, level+1));
}

/* Main function which calculates the depth of deepest odd level leaf.
This function mainly uses depthOfOddLeafUtil() */
int depthOfOddLeaf(struct Node *root)
{
int level = 1, depth = 0;
return depthOfOddLeafUtil(root, level);
}

Check if all leaves are at same level - GeeksforGeeks


http://www.geeksforgeeks.org/check-leaves-level/

bool checkUtil(struct Node *root, int level, int *leafLevel)


{
// Base case
if (root == NULL) return true;

// If a leaf node is encountered


if (root->left == NULL && root->right == NULL)
{
// When a leaf node is found first time
if (*leafLevel == 0)
{
*leafLevel = level; // Set first found leaf's level
return true;
}

// If this is not first leaf node, compare its level with


// first leaf's level
return (level == *leafLevel);
}
// If this node is not leaf, recursively check left and right subtrees
return checkUtil(root->left, level+1, leafLevel) &&
checkUtil(root->right, level+1, leafLevel);
}

/* The main function to check if all leafs are at same level.


It mainly uses checkUtil() */
bool check(struct Node *root)
{
int level = 0, leafLevel = 0;
return checkUtil(root, level, &leafLevel);
}

Print Left View of a Binary Tree - GeeksforGeeks


http://www.geeksforgeeks.org/print-left-view-binary-tree/

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);
}

Deepest left leaf node in a binary tree - GeeksforGeeks


http://www.geeksforgeeks.org/deepest-left-leaf-node-in-a-binary-tree/

void deepestLeftLeafUtil(Node *root, int lvl, int *maxlvl,


bool isLeft, Node **resPtr)
{
// Base case
if (root == NULL)
return;

// Update result if this node is left leaf and its level is more
// than the maxl level of the current result
if (isLeft && !root->left && !root->right && lvl > *maxlvl)
{
*resPtr = root;
*maxlvl = lvl;
return;
}

// Recur for left and right subtrees


deepestLeftLeafUtil(root->left, lvl+1, maxlvl, true, resPtr);
deepestLeftLeafUtil(root->right, lvl+1, maxlvl, false, resPtr);
}

// A wrapper over deepestLeftLeafUtil().


Node* deepestLeftLeaf(Node *root)
{
int maxlevel = 0;
Node *result = NULL;
deepestLeftLeafUtil(root, 0, &maxlevel, false, &result);
return result;
}

Check if two nodes are cousins in a Binary Tree - GeeksforGeeks


http://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/

int isSibling(struct Node *root, struct Node *a, struct Node *b)
{
// Base case
if (root==NULL) return 0;

return ((root->left==a && root->right==b)||


(root->left==b && root->right==a)||
isSibling(root->left, a, b)||
isSibling(root->right, a, b));
}

// Recursive function to find level of Node 'ptr' in a binary tree


int level(struct Node *root, struct Node *ptr, int lev)
{
// base cases
if (root == NULL) return 0;
if (root == ptr) return lev;

// Return level if Node is present in left subtree


int l = level(root->left, ptr, lev+1);
if (l != 0) return l;

// Else search in right subtree


return level(root->right, ptr, lev+1);
}

// Returns 1 if a and b are cousins, otherwise 0


int isCousin(struct Node *root, struct Node *a, struct Node *b)
{
//1. The two Nodes should be on the same level in the binary tree.
//2. The two Nodes should not be siblings (means that they should
// not have the same parent Node).
if ((level(root,a,1) == level(root,b,1)) && !(isSibling(root,a,b)))
return 1;
else return 0;
}

Swap Nodes in Binary tree of every k'th level - GeeksforGeeks


http://www.geeksforgeeks.org/swap-nodes-binary-tree-every-kth-level/

// A utility function swap left- node & right node of tree


// of every k'th level
void swapEveryKLevelUtil( Node *root, int level, int k)
{
// base case
if (root== NULL ||
(root->left==NULL && root->right==NULL) )
return ;

//if current level + 1 is present in swap vector


//then we swap left & right node
if ( (level + 1) % k == 0)
Swap(&root->left, &root->right);

// Recur for left and right subtrees


swapEveryKLevelUtil(root->left, level+1, k);
swapEveryKLevelUtil(root->right, level+1, k);
}

// This function mainly calls recursive function


// swapEveryKLevelUtil()
void swapEveryKLevel(Node *root, int k)
{
// call swapEveryKLevelUtil function with
// initial level as 1.
swapEveryKLevelUtil(root, 1, k);
}

You might also like