Open In App

Maximize sum of path from the Root to a Leaf node in N-ary Tree

Last Updated : 23 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a generic tree consisting of n nodes, the task is to find the maximum sum of the path from the root to the leaf node.

Examples:

Input:


Output: 12
Explanation: The path sum to every leaf from the root are:
For node 4: 1 -> 2 -> 4 = 7
For node 5: 1 -> 2 -> 5 = 8
For node 6: 1 -> 3 -> 6 = 10
For node 7: 1 -> 3 -> 7 = 11
For node 8: 1 -> 3 -> 8 = 12 (maximum)

The maximum path sum is 12 i.e., from root 1 to leaf 8.

Approach:

The given problem can be solved by performing the DFS traversal on the given tree. The idea is to perform the DFS Traversal from the root node of the given generic tree by keeping the track of the sum of values of nodes in each path and if any leaf node occurs then maximize the value of the current sum of path obtained in a variable, say maxSum.

After performing the DFS Traversal, print the value of maxSum as the resultant maximum sum path.

C++
// C++ code of finding Maximize sum of path from 
// the Root to a Leaf node in N-ary Tree

#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    vector<Node*> child;
	Node(int x){
     	data = x; 
    }
};

// Recursive function to calculate the
// maximum sum in a path using DFS
void DFS(Node* root, int sum, int& ans)
{
    // If current node is a leaf node
    if (root->child.size() == 0) {
        ans = max(ans, sum);
        return;
    }

    // Traversing all children of
    // the current node
    for (int i = 0;
         i < root->child.size(); i++) {

        // Recursive call for all
        // the children nodes
        DFS(root->child[i],
            sum + root->child[i]->data, ans);
    }
}

int main() {
  
    Node* root = new Node(1);
    (root->child).push_back(new Node(2));
    (root->child).push_back(new Node(3));
    (root->child[0]->child).push_back(new Node(4));
    (root->child[1]->child).push_back(new Node(6));
    (root->child[0]->child).push_back(new Node(5));
    (root->child[1])->child.push_back(new Node(7));
    (root->child[1]->child).push_back(new Node(8));

    int maxSumPath = 0;
    DFS(root, root->data, maxSumPath);

    cout << maxSumPath;

    return 0;
}
Java
// Java code to find the maximum sum of a path from 
// the Root to a Leaf node in an N-ary Tree

import java.util.ArrayList;

class Node {
    int data;
    ArrayList<Node> child;

    Node(int x) {
        data = x;
        child = new ArrayList<>();
    }
}

class GfG {
  
    // Recursive function to calculate the
    // maximum sum in a path using DFS
    static void DFS(Node root, int sum, int[] ans) {
      
        // If the current node is a leaf node
        if (root.child.size() == 0) {
            ans[0] = Math.max(ans[0], sum);
            return;
        }

        // Traversing all children of
        // the current node
        for (int i = 0; i < root.child.size(); i++) {
          
            // Recursive call for all
            // the children nodes
            DFS(root.child.get(i), sum + root.child.get(i).data, ans);
        }
    }

    public static void main(String[] args) {
  
        Node root = new Node(1);
        root.child.add(new Node(2));
        root.child.add(new Node(3));
        root.child.get(0).child.add(new Node(4));
        root.child.get(1).child.add(new Node(6));
        root.child.get(0).child.add(new Node(5));
        root.child.get(1).child.add(new Node(7));
        root.child.get(1).child.add(new Node(8));

        int[] maxSumPath = new int[1];
        maxSumPath[0] = 0;
        DFS(root, root.data, maxSumPath);

        System.out.println(maxSumPath[0]);
    }
}
Python
# Python code to find the maximum sum of a path from 
# the Root to a Leaf node in an N-ary Tree

class Node:
    def __init__(self, x):
        self.data = x
        self.child = []

# Recursive function to calculate the
# maximum sum in a path using DFS
def DFS(root, sum, ans):
  
    # If the current node is a leaf node
    if len(root.child) == 0:
        ans[0] = max(ans[0], sum)
        return

    # Traversing all children of
    # the current node
    for child in root.child:
      
        # Recursive call for all
        # the children nodes
        DFS(child, sum + child.data, ans)

if __name__ == "__main__":

    root = Node(1)
    root.child.append(Node(2))
    root.child.append(Node(3))
    root.child[0].child.append(Node(4))
    root.child[1].child.append(Node(6))
    root.child[0].child.append(Node(5))
    root.child[1].child.append(Node(7))
    root.child[1].child.append(Node(8))

    maxSumPath = [0]
    DFS(root, root.data, maxSumPath)

    print(maxSumPath[0])
C#
// C# code to find the maximum sum of a path from 
// the Root to a Leaf node in an N-ary Tree

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public List<Node> child;

    public Node(int x) {
        data = x;
        child = new List<Node>();
    }
}

class GfG {
  
    // Recursive function to calculate the
    // maximum sum in a path using DFS
    static void DFS(Node root, int sum, ref int ans) {
      
        // If the current node is a leaf node
        if (root.child.Count == 0) {
            ans = Math.Max(ans, sum);
            return;
        }

        // Traversing all children of
        // the current node
        foreach (var child in root.child) {
          
            // Recursive call for all
            // the children nodes
            DFS(child, sum + child.data, ref ans);
        }
    }

    static void Main() {

        Node root = new Node(1);
        root.child.Add(new Node(2));
        root.child.Add(new Node(3));
        root.child[0].child.Add(new Node(4));
        root.child[1].child.Add(new Node(6));
        root.child[0].child.Add(new Node(5));
        root.child[1].child.Add(new Node(7));
        root.child[1].child.Add(new Node(8));

        int maxSumPath = 0;
        DFS(root, root.data, ref maxSumPath);

        Console.WriteLine(maxSumPath);
    }
}
JavaScript
// JavaScript code to find the maximum sum of a path from 
// the Root to a Leaf node in an N-ary Tree

class Node {
    constructor(x) {
        this.data = x;
        this.child = [];
    }
}

// Recursive function to calculate the
// maximum sum in a path using DFS
function DFS(root, sum, ans) {

    // If the current node is a leaf node
    if (root.child.length === 0) {
        ans[0] = Math.max(ans[0], sum);
        return;
    }

    // Traversing all children of
    // the current node
    for (let i = 0; i < root.child.length; i++) {
    
        // Recursive call for all
        // the children nodes
        DFS(root.child[i], sum + root.child[i].data, ans);
    }
}

let root = new Node(1);
root.child.push(new Node(2));
root.child.push(new Node(3));
root.child[0].child.push(new Node(4));
root.child[1].child.push(new Node(6));
root.child[0].child.push(new Node(5));
root.child[1].child.push(new Node(7));
root.child[1].child.push(new Node(8));

let maxSumPath = [0];
DFS(root, root.data, maxSumPath);

console.log(maxSumPath[0]);

 
 


Output
12

Time Complexity: O(n), where n is the number of nodes in tree
Auxiliary Space: O(n)


Next Article

Similar Reads