Category: Binary Tree

DSatur Algorithm for Graph Coloring

  #include #include #include #include using namespace std;  struct nodeInfo {    int sat;     int deg;     int vertex; };struct maxSat {    bool operator()(const nodeInfo& lhs,                    const nodeInfo& rhs) const    {                                        return tie(lhs.sat, lhs.deg, lhs.vertex)               > tie(rhs.sat, rhs.deg, rhs.vertex);    }};  class Graph {          int n;          vector adj;  public:        Graph(int numNodes)    {        n = numNodes;        adj.resize(n, vector());    }    ~Graph() { adj.clear(); }          void addEdge(int u, int v);              void DSatur();};  void Graph::addEdge(int u, int v){    adj[u].push_back(v);    adj[v].push_back(u);}  void Graph::DSatur(){    int u, i;    vector used(n, false);    vector c(n), […]

Continue Reading

Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes

  #include using namespace std;  class Node {public:    int val;    Node *left, *right;    Node(int val)    {        this->val = val;        left = right = NULL;    }};  Node* buidSymmetericTree(Node* root1,                         Node* root2){        if (root1 == NULL and root2 == NULL) {        return NULL;    }          if (root1 == NULL) {                          Node* node = new Node(root2->val);        root1 = node;    }          if (root2 == NULL) {                          Node* node = new Node(root1->val);        root2 = node;    }                  if (root1->val != root2->val) {        int temp = root1->val […]

Continue Reading

Check if all elements of given Linked List corresponds to a downward path from any node in given Binary Tree

  #include “bits/stdc++.h”using namespace std;  struct listNode {    int val;    struct listNode* next;          listNode(int data)    {        this->val = data;        next = NULL;    }};  struct treeNode {    int val;    treeNode* right;    treeNode* left;          treeNode(int data)    {        this->val = data;        this->left = NULL;        this->right = NULL;    }};  bool isPathUtil(listNode* curList,                treeNode* curTree){            if (curList == NULL)        return true;          if (curTree == NULL)        return false;      if (curList->val == curTree->val) {                          return isPathUtil(curList->next,                          curTree->left)               || isPathUtil(curList->next,                             curTree->right);    }    else {                  return false;    }}  bool isPath(listNode* head, treeNode* root){              if (root == NULL)        return false;              if (head == […]

Continue Reading

Minimize sum of node values by filling given empty Tree such that each node is GCD of its children

#include using namespace std;  class Node {public:    int val;    Node *left, *right;    Node(int val)    {        this->val = val;        left = NULL;        right = NULL;    }};  class Tree {public:    unordered_map depth;              int findDepth(Node* cur)    {        int mx = 0;        if (cur->left) {            mx = findDepth(cur->left);        }        if (cur->right) {            mx = max(mx, findDepth(cur->right));        }                          return depth[cur] = mx + 1;    }              int dfs(Node* cur, bool flag, int parValue)    {        if (parValue != -1) {            if (flag)                cur->val = parValue;            else                cur->val = parValue * 2;        }        int […]

Continue Reading

Minimum value to be added at each level in Binary Tree to make all level sum equal

import java.util.*;  class Node {    int data;    Node left, right;    public Node(int item)    {        data = item;        left = right = null;    }}  class BinaryTree {    Node root;    public BinaryTree()    {        root = null;    }                  static ArrayList levelOrderAP(Node root)    {                  ArrayList finalAns = new ArrayList();                  if (root == null) {            return finalAns;        }                  Utilfun(root, 0, finalAns);        int maxi = Integer.MIN_VALUE;                  for (int ele : finalAns) {            maxi = Math.max(maxi, ele);        }                        for (int i = 0; i < finalAns.size(); i++) {            int […]

Continue Reading

Test Case Generation | Set 6 (Random Unweighted Binary Tree)

  #include using namespace std;    vector generateBinaryTree(int n){                        vector options = { 0, 1, 2 };                        map mp;                queue q;            q.push(1);            vector v;                int count = 1;                mp[1] = 1;            while (!q.empty() or count < n) {                                            int front;                  if(!q.empty()) {                                                    front = q.front();                                                                q.pop();        }                                                          int numberOfChilds          = options[rand() % (options.size())];                            if (count >= n)            continue;                                        while (numberOfChilds–) {                                                                int child = rand() % n + 1;                                        while (mp[child]) {                child++;                if (child > n) {                    child = 1;                }            }                                        count++;                            mp[child] […]

Continue Reading

Queries to find the sum of weights of all nodes with vertical width from given range in a Binary Tree

  #include using namespace std;  struct Node {    int data;    Node* left;    Node* right;};  Node* newNode(int d){    Node* n = new Node;    n->data = d;    n->left = NULL;    n->right = NULL;    return n;}  void findwt(Node* root, int wt[],            map& um,            int width = 0){        if (root == NULL) {        return;    }              um[width] += wt[root->data];          findwt(root->left, wt, um,           width – 1);          findwt(root->right, wt, um,           width + 1);}  void solveQueries(int wt[], Node* root,                  vector queries){            map um;          findwt(root, wt, um);              int x = 0;          for […]

Continue Reading

Modify Binary Tree by replacing each node with the product of all remaining nodes

  #include using namespace std;  class Node {public:    int data;    Node *left, *right;          Node(int data)    {        this->data = data;        left = NULL;        right = NULL;    }};  Node* newNode(int value){    Node* temp = new Node(value);    return (temp);}  int findProduct(Node* root){        if (root == NULL)        return 1;              return (root->data            * findProduct(root->left)            * findProduct(root->right));}  void display(Node* root){        if (root == NULL)        return;              display(root->left);          cout data right);}  void convertTree(int product,                 Node* root){        if (root == NULL)        return;              root->data = product / (root->data);          convertTree(product, root->left);          convertTree(product, root->right);}  int main(){        Node* root = newNode(1);    root->left […]

Continue Reading

Tutorial on Binary Tree

The tree is a hierarchical Data Structure. A binary tree is a tree that has at most two children. The node which is on the left of the Binary Tree is called “Left-Child” and the node which is the right is called “Right-Child”. Also, the smaller tree or the subtree in the left of the […]

Continue Reading

Modify Binary Tree by replacing each node with nearest power of minimum of previous level

import math  class TreeNode:    def __init__(self, val=0, left=None, right=None):        self.val = val        self.left = left        self.right = right    def nearestPow(x, base):    k = int(math.log(x, base))    if abs(base**k – x) < abs(base**(k+1) - x):        return base**k    else:        return base**(k+1)  def printLevelOrder(root):          if root is None:        return              q = []          q.append(root)      while q:                          count = len(q)                                  while count > 0:            temp = q.pop(0)            print(temp.val, end=’ ‘)                                      if temp.left:                q.append(temp.left)                                      if temp.right:                q.append(temp.right)                          count -= 1    def replaceNodes(root):              que = [root]          lvl = 1              minPrev = root.val              minCurr = […]

Continue Reading