• Source
    1. #include <iostream>
    2. #include <vector>
    3.  
    4. using namespace std;
    5.  
    6. // A node in an n-ary tree
    7. struct Node
    8. {
    9. int value;
    10. vector<Node*> children;
    11. };
    12.  
    13. // Find the sum of the largest increasing branch in an n-ary tree
    14. int largestIncreasingBranchSum(Node* node)
    15. {
    16. // Base case: If the node has no children, it is the leaf node
    17. // and the sum of the branch is the value of the node
    18. if (node->children.empty())
    19. {
    20. return node->value;
    21. }
    22.  
    23. // Initialize the sum of the branch to the value of the node
    24. int sum = node->value;
    25.  
    26. // Iterate through the children of the node
    27. for (Node* child : node->children)
    28. {
    29. // If the value of the node is less than the value of the child,
    30. // add the sum of the largest increasing branch starting from the child
    31. if (node->value < child->value)
    32. {
    33. sum += largestIncreasingBranchSum(child);
    34. }
    35. }
    36.  
    37. // Return the sum of the branch
    38. return sum;
    39. }
    40.  
    41. int main()
    42. {
    43. // Create the example n-ary tree
    44. Node* root = new Node{10};
    45. root->children.push_back(new Node{6});
    46. root->children.push_back(new Node{12});
    47. root->children[0]->children.push_back(new Node{4});
    48. root->children[0]->children.push_back(new Node{8});
    49. root->children[1]->children.push_back(new Node{11});
    50. root->children[1]->children.push_back(new Node{13});
    51.  
    52. // Find the sum of the largest increasing branch
    53. int sum = largestIncreasingBranchSum(root);
    54.  
    55. // Print the sum
    56. std::cout << "Sum of the largest increasing branch: " << sum << std::endl;
    57.  
    58. return 0;
    59. }