Сумма двоюродных братьев данного узла в двоичном дереве
Учитывая двоичное дерево и значение данных узла. Задача состоит в том, чтобы найти сумму двоюродных узлов данного узла. Если у данного узла нет кузенов, верните -1.
 Примечание: дано, что все узлы имеют разные значения и данный узел существует в дереве.
Примеры:
Вход: 
                1
              / 
             3 7
           /  / 
          6 5 4 13
             / / 
            10 17 15
         ключ = 13
Выход: 11
Двоюродные узлы - 5 и 6, что дает сумму 11. 
Вход:
                1
              / 
             3 7
           /  / 
          6 5 4 13
             / / 
            10 17 15
           ключ = 7
Выход: -1
Нет узлов-родственников узла со значением 7.
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Подход: подход заключается в обходе дерева в порядке уровней. Выполняя обход порядка уровней, найдите сумму дочерних узлов следующего уровня. Добавьте к сумме значение дочернего узла и проверьте, является ли какой-либо из дочерних узлов целевым узлом или нет. Если да, то не добавляйте к сумме значение ни одного из дочерних элементов. После прохождения текущего уровня, если целевой узел присутствует на следующем уровне, завершите обход порядка уровней, и найденная сумма будет суммой двоюродных узлов.
Below is the implementation of the above approach:
C++
| // CPP program to find sum of cousins// of given node in binary tree.#include <bits/stdc++.h>usingnamespacestd; // A Binary Tree NodestructNode {    intdata;    structNode *left, *right;}; // A utility function to create a new// Binary Tree NodestructNode* newNode(intitem){    structNode* temp = (structNode*)malloc(sizeof(structNode));    temp->data = item;    temp->left = temp->right = NULL;    returntemp;} // Function to find sum of cousins of// a given node.intfindCousinSum(Node* root, intkey){    if(root == NULL)        return-1;     // Root node has no cousins so return -1.    if(root->data == key) {        return-1;    }     // To store sum of cousins.    intcurrSum = 0;     // To store size of current level.    intsize;     // To perform level order traversal.    queue<Node*> q;    q.push(root);     // To represent that target node is    // found.    boolfound = false;     while(!q.empty()) {         // If target node is present at        // current level, then return        // sum of cousins stored in currSum.        if(found == true) {            returncurrSum;        }         // Find size of current level and        // traverse entire level.        size = q.size();        currSum = 0;         while(size) {            root = q.front();            q.pop();             // Check if either of the existing            // children of given node is target            // node or not. If yes then set            // found equal to true.            if((root->left && root->left->data == key)                || (root->right && root->right->data == key)) {                found = true;            }             // If target node is not children of            // current node, then its childeren can be cousin            // of target node, so add their value to sum.            else{                if(root->left) {                    currSum += root->left->data;                    q.push(root->left);                }                 if(root->right) {                    currSum += root->right->data;                    q.push(root->right);                }            }             size--;        }    }     return-1;} // Driver Codeintmain(){    /*                1              /               3    7           /    /           6   5  4  13             /  /             10 17 15    */     structNode* root = newNode(1);    root->left = newNode(3);    root->right = newNode(7);    root->left->left = newNode(6);    root->left->right = newNode(5);    root->left->right->left = newNode(10);    root->right->left = newNode(4);    root->right->right = newNode(13);    root->right->left->left = newNode(17);    root->right->left->right = newNode(15);     cout << findCousinSum(root, 13) << "
";     cout << findCousinSum(root, 7) << "
";    return0;} | 
Java
| // Java program to find sum of cousins// of given node in binary tree.importjava.util.*;classSol{     // A Binary Tree NodestaticclassNode {    intdata;    Node left, right;}; // A utility function to create a new// Binary Tree NodestaticNode newNode(intitem){    Node temp = newNode();    temp.data = item;    temp.left = temp.right = null;    returntemp;} // Function to find sum of cousins of// a given node.staticintfindCousinSum(Node root, intkey){    if(root == null)        return-1;     // Root node has no cousins so return -1.    if(root.data == key)     {        return-1;    }     // To store sum of cousins.    intcurrSum = 0;     // To store size of current level.    intsize;     // To perform level order traversal.    Queue<Node> q=newLinkedList<Node>();    q.add(root);     // To represent that target node is    // found.    booleanfound = false;     while(q.size() > 0)     {         // If target node is present at        // current level, then return        // sum of cousins stored in currSum.        if(found == true)         {            returncurrSum;        }         // Find size of current level and        // traverse entire level.        size = q.size();        currSum = 0;         while(size > 0)         {            root = q.peek();            q.remove();             // Check if either of the existing            // children of given node is target            // node or not. If yes then set            // found equal to true.            if((root.left!=null&& root.left.data == key)                || (root.right!=null&& root.right.data == key))             {                found = true;            }             // If target node is not children of            // current node, then its childeren can be cousin            // of target node, so add their value to sum.            else            {                if(root.left != null)                 {                    currSum += root.left.data;                    q.add(root.left);                }                 if(root.right != null)                 {                    currSum += root.right.data;                    q.add(root.right);                }            }             size--;        }    }     return-1;} // Driver Codepublicstaticvoidmain(String args[]){    /*                1            /             3 7        /  /         6 5 4 13            / /             10 17 15    */     Node root = newNode(1);    root.left = newNode(3);    root.right = newNode(7);    root.left.left = newNode(6);    root.left.right = newNode(5);    root.left.right.left = newNode(10);    root.right.left = newNode(4);    root.right.right = newNode(13);    root.right.left.left = newNode(17);    root.right.left.right = newNode(15);     System.out.print( findCousinSum(root, 13) + "
");     System.out.print( findCousinSum(root, 7) + "
");}} // This code is contributed by Arnab Kundu | 
Python3
| """ Python3 program to find sum of cousins of given node in binary tree """ # A Binary Tree Node # Utility function to create a new tree node classnewNode:      # Constructor to create a newNode     def__init__(self, data):         self.data =data         self.left =None        self.right =None # Function to find sum of cousins of # a given node. deffindCousinSum( root, key):     if(root ==None):         return-1     # Root node has no cousins so return -1.     if(root.data ==key):        return-1          # To store sum of cousins.     currSum =0     # To store size of current level.     size =0     # To perform level order traversal.     q =[]     q.append(root)      # To represent that target node is     # found.     found =False     while(len(q)):          # If target node is present at         # current level, then return         # sum of cousins stored in currSum.         if(found ==True):             returncurrSum                  # Find size of current level and         # traverse entire level.         size =len(q)        currSum =0         while(size):             root =q[0]             q.pop(0)              # Check if either of the existing             # children of given node is target             # node or not. If yes then set             # found equal to true.             if((root.left androot.left.data ==key) or                (root.right androot.right.data ==key)) :                found =True                         # If target node is not children of current             # node, then its childeren can be cousin             # of target node, so add their value to sum.             else:                if(root.left):                    currSum +=root.left.data                     q.append(root.left)                                  if(root.right) :                    currSum +=root.right.data                     q.append(root.right)              size -=1    return-1                         # Driver Codeif__name__ =="__main__":     """                 1             /              3 7         /  /          6 5 4 13             / /              10 17 15     """    root =newNode(1)     root.left =newNode(3)     root.right =newNode(7)     root.left.left =newNode(6)     root.left.right =newNode(5)     ro
            РЕКОМЕНДУЕМЫЕ СТАТЬИ |