You are on page 1of 23

#include <stdio.

h>
#include <stdlib.h>

struct node {
int data;

struct node *leftChild;


struct node *rightChild;
};

struct node *root = NULL;

void insert(int data) {


struct node *tempNode = (struct node*) malloc(sizeof(struct
node));
struct node *current;
struct node *parent;

tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;

//if tree is empty


if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;

while(1) {
parent = current;

//go to left of the tree


if(data < parent->data) {
current = current->leftChild;

//insert to the left


if(current == NULL) {
parent->leftChild = tempNode;
return;
}
} //go to right of the tree
else {
current = current->rightChild;

//insert to the right


if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}

struct node* search(int data) {


struct node *current = root;
printf("Visiting elements: ");

while(current->data != data) {
if(current != NULL)
printf("%d ",current->data);

//go to left tree


if(current->data > data) {
current = current->leftChild;
}
//else go to right tree
else {
current = current->rightChild;
}

//not found
if(current == NULL) {
return NULL;
}
}

return current;
}

void pre_order_traversal(struct node* root) {


if(root != NULL) {
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}

void inorder_traversal(struct node* root) {


if(root != NULL) {
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}

void post_order_traversal(struct node* root) {


if(root != NULL) {
post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
printf("%d ", root->data);
}
}

LEFT VIEW:

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

RIGHT VIEW:

Right view of following tree is 1 3 7 8

1
/ \
2 3
/ \ / \
4 5 6 7
\
8

void rightViewUtil(struct Node *root, int level, int


*max_level)
{
    // Base Case
    if (root==NULL)  return;
 
    // If this is the last Node of its level
    if (*max_level < level)
    {
        printf("%d\t", root->data);
        *max_level = level;
    }
 
    // Recur for right subtree first, then left subtree
    rightViewUtil(root->right, level+1, max_level);
    rightViewUtil(root->left, level+1, max_level);
}
 
// A wrapper over rightViewUtil()
void rightView(struct Node *root)
{
    int max_level = 0;
    rightViewUtil(root, 1, &max_level);
}

USING QUEUE RIGHT VIEW:

void printRightView(Node* root)


{
    if (!root)
        return;
 
    queue<Node*> q;
    q.push(root);
 
    while (!q.empty())
    {   
        // number of nodes at current level
        int n = q.size();
         
        // Traverse all nodes of current level
        for(int i = 1; i <= n; i++)
        {
            Node* temp = q.front();
            q.pop();
                 
            // Print the right most element
            // at the level
            if (i == n)
                cout<<temp->data<<" ";
             
            // Add left node to queue
            if (temp->left != NULL)
                q.push(temp->left);
 
            // Add right node to queue
            if (temp->right != NULL)
                q.push(temp->right);
        }
    }
}

TOP VIEW:

1
/ \
2 3
/ \ / \
4 5 6 7
Top view of the above binary tree is
4 2 1 3 7

1
/ \
2 3
\
4
\
5
\
6
Top view of the above binary tree is
2 1 3 6

void topview(Node* root)


{
    if (root == NULL)
        return;
    queue<Node*> q;
    map<int, int> m;
    int hd = 0;
    root->hd = hd;
 
    // push node and horizontal distance to queue
    q.push(root);
 
    cout << "The top view of the tree is : \n";
 
    while (q.size()) {
        hd = root->hd;
 
        // count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        if (m.count(hd) == 0)
            m[hd] = root->data;
        if (root->left) {
            root->left->hd = hd - 1;
            q.push(root->left);
        }
        if (root->right) {
            root->right->hd = hd + 1;
            q.push(root->right);
        }
        q.pop();
        root = q.front();
    }
 
    for (auto i = m.begin(); i != m.end(); i++) {
        cout << i->second << " ";
    }
}

ANOTHER APPROCH:

void fillMap(Node* root, int d, int l,


             map<int, pair<int, int> >& m)
{
    if (root == NULL)
        return;
 
    if (m.count(d) == 0) {
        m[d] = make_pair(root->data, l);
    }
    else if (m[d].second > l) {
        m[d] = make_pair(root->data, l);
    }
 
    fillMap(root->left, d - 1, l + 1, m);
    fillMap(root->right, d + 1, l + 1, m);
}
 
// function should print the topView of
// the binary tree
void topView(struct Node* root)
{
 
    // map to store the pair of node value and its level
    // with respect to the vertical distance from root.
    map<int, pair<int, int> > m;
 
    // fillmap(root,vectical_distance_from_root,level_of_node,map)
    fillMap(root, 0, 0, m);
 
    for (auto it = m.begin(); it != m.end(); it++) {
        cout << it->second.first << " ";
    }
}

SUM TREE:

A SumTree is a Binary Tree where the value of a node is equal to the sum of
the nodes present in its left subtree and right subtree. An empty tree is
SumTree and the sum of an empty tree can be considered as 0. A leaf node is
also considered as SumTree.

int sum(struct node *root)


{
   if(root == NULL)
     return 0;
   return sum(root->left) + root->data + sum(root->right);
}
 
/* returns 1 if sum property holds for the given
    node and both of its children */
int isSumTree(struct node* node)
{
    int ls, rs;
 
    /* If node is NULL or it's a leaf node then
       return true */
    if(node == NULL ||
            (node->left == NULL && node->right == NULL))
        return 1;
 
   /* Get sum of nodes in left and right subtrees */
   ls = sum(node->left);
   rs = sum(node->right);
 
   /* if the node and both of its children satisfy the
       property return 1 else 0*/
    if((node->data == ls + rs)&&
            isSumTree(node->left) &&
            isSumTree(node->right))
        return 1;
 
   return 0;
}

INTERNAL NODE:
void printNonLeafNodes(Node* root) {
   queue<Node*> treeNodes;
   treeNodes.push(root);
   while (!treeNodes.empty()) {
      Node* curr = treeNodes.front();
      treeNodes.pop();
      bool isInternal = 0;
      if (curr->left) {
         isInternal = 1;
         treeNodes.push(curr->left);
      }
      if (curr->right) {
         isInternal = 1;
         treeNodes.push(curr->right);
      }
      if (isInternal)
         cout<<curr->data<<"\t";
   }
}

FULL NODE:

void printFullNode(Node *root){


   if (root != NULL){
      printFullNode(root->left);
      if (root->left != NULL && root->right != NULL)
         cout<<root->data<<"\t";
      printFullNode(root->right);
   }
}
PRINT ODD NODES:
Node* newNode(int item){
   Node* temp = new Node;
   temp->key = item;
   temp->left = temp->right = NULL;
   return temp;
}
Node* insertNode(Node* node, int key){
   if (node == NULL)
      return newNode(key);
   if (key < node->key)
      node->left = insertNode(node->left, key);
   else
      node->right = insertNode(node->right, key);
   return node;
}
void printOddNodes(Node* root){
   if (root != NULL) {
      printOddNodes(root->left);
      if (root->key % 2 != 0)
         cout<<root->key<<"\t";
      printOddNodes(root->right);
   }
}
LEVELS:
//it will print levels of a tree
void levels(Node* root){
   if (root==NULL)
      return;
   queue<pair<struct Node*, int> >que;
   que.push({root, 1});
   pair<struct Node*, int> par;
   while (!que.empty()) {
      par = que.front();
      que.pop();
      cout << "Level of " << par.first->data << " is " <<
par.second << "\n";
      if (par.first->left)
         que.push({ par.first->left, par.second + 1 });
      if (par.first->right)
         que.push({ par.first->right, par.second + 1 });
   }
}
NODES BETWEEN LEVELS:
void printNodesAtLevel(Node* root, int low, int high){
   queue <Node *> Q;
   Node *marker = new Node;
   int level = 1;
   Q.push(root);
   Q.push(marker);
   while (Q.empty() == false){
      Node *n = Q.front();
      Q.pop();
      if (n == marker){
         cout << endl;
         level++;
         if (Q.empty() == true || level > high) break;
         Q.push(marker);
         continue;
      }
      if (level >= low)
         cout<<n->key<<" ";
      if (n->left != NULL) Q.push(n->left);
      if (n->right != NULL) Q.push(n->right);
   }
}

Print path between any two nodes in a


Binary Tree
bool path(Node* root, vector<int>& arr, int x){
   if (!root)
      return false;
   // push the node's value in 'arr'
   arr.push_back(root->data);
   // if it is the required node
   // return true
   if (root->data == x)
      return true;
   if (path(root->left, arr, x) || path(root->right, arr, x))
      return true;
   arr.pop_back();
   return false;
}
// Function to print the path between
// any two nodes in a binary tree
void printPath(Node* root, int n1, int n2){
   // vector to store the path
   vector<int> path1;
   vector<int> path2;
   path(root, path1, n1);
   path(root, path2, n2);
   int intersection = -1;
   int i = 0, j = 0;
   while (i != path1.size() || j != path2.size()) {
      if (i == j && path1[i] == path2[j]) {
         i++;
         j++;
      } else {
         intersection = j - 1;
         break;
      }
   }
   // Print the required path
   for (int i = path1.size() - 1; i > intersection; i--)
      cout << path1[i] << " ";
   for (int i = intersection; i < path2.size(); i++)
      cout << path2[i] << " ";
}
PRINT THE NOES AT ODD LEVEL:
void printOddNodes(Node *root, bool isOdd = true)
{
    // If empty tree
    if (root == NULL)
      return;
 
    // If current node is of odd level
    if (isOdd)
       cout << root->data << " " ;
 
    // Recur for children with isOdd
    // switched.
    printOddNodes(root->left, !isOdd);
    printOddNodes(root->right, !isOdd);
}
PRINT THE KTH DISTANCE:
void printKDistant(struct node *root , int k)   
{
   if(root == NULL|| k < 0 )
      return;
   if( k == 0 )
   {
      printf( "%d ", root->data );
      return ;
   }
      
      printKDistant( root->left, k-1 ) ;
      printKDistant( root->right, k-1 ) ;
    
}

DEGREE:

#include <stdio.h>

#define MAX 100

int main()

int btree[MAX];

int degtree[MAX];

for(int i=0; i<MAX; i++) {

btree[i] = -1;
degtree[i] = 0;

int n;

int leaf_node = 0;

scanf("%d", &n);

for(int i=1; i<=n ; i++) {

scanf("%d", &btree[i]);

for(int p=1; p<=n; p++)

if(btree[2*p] != -1)

degtree[p]++;

if(btree[2*p + 1] != -1)

degtree[p]++;

}
for(int p=1; p<=n; p++)

if(degtree[p] == 0 && btree[p] != -1)

leaf_node++;

printf("%d ", leaf_node);

for(int p=1; p<=n; p++)

if(btree[p] != -1)

printf("%d ", degtree[p]);

KTH NODE:

LARGEST AND SMALLEST:

int findMax(Node* root)


{
    // Base case
    if (root == NULL)
        return INT_MIN;
 
    // Return maximum of 3 values:
    // 1) Root's data 2) Max in Left Subtree
    // 3) Max in right subtree
    int res = root->data;
    int lres = findMax(root->left);
    int rres = findMax(root->right);
    if (lres > res)
        res = lres;
    if (rres > res)
        res = rres;
    return res;
}
int findMin(Node *root)
    {
        //code
        if(root==NULL)
     {
         return INT_MAX;
     }
       int res=root->data;
       int left=findMin(root->left);
       int right=findMin(root->right);
       if(left<res)
       {
           res=left;
       }
       if(right<res)
       {
           res=right;
       }
       return res;
    }

COUNT:
1.int countnodes(struct node *root)
2.{
3. if(root != NULL)
4. {
5. countnodes(root->left);
6. count++;
7. countnodes(root->right);
8. }
9. return count;
10. }

int countSubtrees(Node* root, int &count)


{
    // base case: empty tree
    if (root == nullptr) {
        return INT_MIN;
    }
 
    // if the root is a leaf node, increase the count and return root node data
    if (root->left == nullptr && root->right == nullptr)
    {
        count++;
        return root->data;
    }
 
    // recur for the left and right subtree
    int left = countSubtrees(root->left, count);
    int right = countSubtrees(root->right, count);
 
    // 1. The left subtree is empty, and the right subtree data matches the root
    // 2. The right subtree is empty, and the left subtree data matches the root
    // 3. Both left and right subtrees are non-empty, and their data matches the root
 
    if ((left == INT_MIN && right == root->data) ||
        (right == INT_MIN && left == root->data) ||
        (left == right && left == root->data))
    {
        // increase the count and return root node data
        count++;
        return root->data;
    }
 
    // return infinity if root's data doesn't match with left or right subtree
    return INT_MAX;
}
 
// The main function to count all subtrees having the same value of nodes
int countSubtrees(Node* root)
{
    int count = 0;
    countSubtrees(root, count);
 
    return count;
}

int cur = 1, mx = 0;
int node;
struct Node* previous = NULL;
 
// Find the inorder traversal of the BST
void inorder(struct Node* root)
{
    // If root is NULL then return
    if (root == NULL) {
        return;
    }
    inorder(root->left);
    if (previous != NULL) {
        // If the previous value is equal to the current value
        // then increase the count
        if (root->val == previous->val) {
            cur++;
        }
        // Else initialize the count by 1
        else {
            cur = 1;
        }
    }
    // If current count is greater than the max count
    // then update the mx value
    if (cur > mx) {
        mx = cur;
        node = root->val;
    }
    // Make the current Node as previous
    previous = root;
    inorder(root->right);
}
 
// Utility function
int findnode(struct Node* root)
{
    inorder(root);
    return node;
}

1. public void inOrderMorris(BinaryNode root) { 


2. BinaryNode current = root; 
3. BinaryNode pre = null; 
4.  
5. while (current != null) { 
6. if (current.left == null) { 
7. process(current); 
8. current = current.right; 
9. } else { 
10. pre = current.left; 
11.  
12. while (pre.right != null && pre.right != current) { 
13. pre = pre.right; 
14. } 
15.  
16. if (pre.right == null) { 
17. pre.right = current; 
18. current = current.left; 
19. } else { 
20. pre.right = null; 
21. process(current); 
22. current = current.right; 
23. } 
24. } 
25. } 
26. } 

DUPLICATE:

bool checkDupUtil(Node* root, unordered_set<int> &s)


{
    // If tree is empty, there are no
    // duplicates.
    if (root == NULL)
       return false;
 
    // If current node's data is already present.
    if (s.find(root->data) != s.end())
       return true;
 
    // Insert current node
    s.insert(root->data);
     
    // Recursively check in left and right
    // subtrees.
    return checkDupUtil(root->left, s) ||
           checkDupUtil(root->right, s);
}
 
// To check if tree has duplicates
bool checkDup(struct Node* root)
{
    unordered_set<int> s;
    return checkDupUtil(root, s);
}

CHECK IF BINARY TREE OR NOT

/* Returns true if a binary tree is a binary search tree */


int isBST(struct node* node)
{
if (node == NULL)
return 1;

/* false if the max of the left is > than us */


if (node->left!=NULL && maxValue(node->left) > node->data)
return 0;

/* false if the min of the right is <= than us */


if (node->right!=NULL && minValue(node->right) < node->data)
return 0;
/* false if, recursively, the left or right is not a BST */
if (!isBST(node->left) || !isBST(node->right))
return 0;

/* passing all that, it's a BST */


return 1;
}
LEAF NODE:
void findLeafNode(Node* root) {
   if (!root)
      return;
   if (!root->left && !root->right) {
      cout<<root->data<<"\t";
      return;
   }
   if (root->right)
      findLeafNode(root->right);
   if (root->left)
      findLeafNode(root->left);
}
DEEPEST LEFT LEAF NODE:
void getDeepestLeftLeafNode(Node *root, bool isLeftNode, Node
**resultPointer) {
   if (root == NULL) {
      return;
   }
   if (isLeftNode && !root->left && !root->right) {
      *resultPointer = root;
      return;
   }
   getDeepestLeftLeafNode(root->left, true, resultPointer);
   getDeepestLeftLeafNode(root->right, false, resultPointer);
}
DEPTH OF DEEPEST NODE:

int oddLeafDepthInTree(struct Node *root, int level) {


   if (root == NULL) {
      return 0;
   }
   if (root->left == NULL && root->right == NULL && level % 2 == 1)
{
      return level;
   }
   return max(oddLeafDepthInTree(root->left, level + 1),
oddLeafDepthInTree(root->right, level + 1));
}

Print path from root to a given node in a


binary tree
bool hasPath(Node *root, vector<int>& arr, int x)
{
    // if root is NULL
    // there is no path
    if (!root)
        return false;
     
    // push the node's value in 'arr'
    arr.push_back(root->data);   
     
    // if it is the required node
    // return true
    if (root->data == x)   
        return true;
     
    // else check whether the required node lies
    // in the left subtree or right subtree of
    // the current node
    if (hasPath(root->left, arr, x) ||
        hasPath(root->right, arr, x))
        return true;
     
    // required node does not lie either in the
    // left or right subtree of the current node
    // Thus, remove current node's value from
    // 'arr'and then return false   
    arr.pop_back();
    return false;           
}
 
// function to print the path from root to the
// given node if the node lies in the binary tree
void printPath(Node *root, int x)
{
    // vector to store the path
    vector<int> arr;
     
    // if required node 'x' is present
    // then print the path
    if (hasPath(root, arr, x))
    {
        for (int i=0; i<arr.size()-1; i++)   
            cout << arr[i] << "->";
        cout << arr[arr.size() - 1];   
    }
     
    // 'x' is not present in the binary tree
    else
        cout << "No Path";
}

You might also like