Site icon

Find maximum sum, root to leaf path in binary tree (Java/ recursive/ example)

Fig 1: Root to leaf paths – Binary tree

The root to leaf paths in a binary tree are as follows:

S. No.Root to leaf node Sum of path
1A -> B -> D 120
2A -> B -> E 90
3A -> C -> F 110
4A -> C -> G 140

So, clearly the path A -> C -> G  has maximum sum of 140, which is expected output of our problem.

Algorithm: find maximum sum, root to leaf path in a binary tree

Fig 2: Root to leaf paths

Program – find maximum sum, root to leaf path in binary tree ( Java)

1.) MaxSumPathRoot2Leaf:

package org.learn.Question;

import java.util.Arrays;

public class MaxSumPathRoot2Leaf {
	private static int maxSum = 0;
	private static int[] arr;

	public static void maxSumPath(Node root, int[] path) {
		maxSum = Integer.MIN_VALUE;
		maxSumPathRoot2Leaf(root, path, 0, 0);
		System.out.println("Maximum Sum :" + maxSum);
		System.out.println("Root to Leaf Path: " + Arrays.toString(arr));
	}

	public static void maxSumPathRoot2Leaf(Node root, int[] path, int index, int sum) {
		if (null == root) {
			return;
		}
		path[index++] = root.data;
		sum += root.data;
		if (root.left == null && root.right == null) {
			if (sum > maxSum) {
				maxSum = sum;
				arr = Arrays.copyOf(path, index);
			}
			return;
		}
		maxSumPathRoot2Leaf(root.left, path, index, sum);
		maxSumPathRoot2Leaf(root.right, path, index, sum);
		return;
	}
}

2.) Node Class:

package org.learn.Question;

public class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int num) {
		this.data = num;
		this.left = null;
		this.right = null;
	}

	public Node() {
		this.left = null;
		this.right = null;
	}
	
	public static Node createNode(int number) {
		return new Node(number);
	}
}

3.) App Class:

package org.learn.Client;

import org.learn.Question.MaxSumPathRoot2Leaf;
import org.learn.Question.Node;

public class App {
	public static void main(String[] args) {
		Node root = Node.createNode(50);
		root.left = Node.createNode(30);
		root.right = Node.createNode(30);
		// left sub tree
		root.left.left = Node.createNode(40);
		root.left.right = Node.createNode(10);

		// right subtree
		root.right.left = Node.createNode(30);
		root.right.right = Node.createNode(60);

		int[] path = new int[512];
		MaxSumPathRoot2Leaf.maxSumPath(root, path);
	}
}

Output – maximum sum, root to leaf path in a binary tree (java)

Maximum Sum :140
Root to Leaf Path: [50, 30, 60]

Download code-maximum sum, root to leaf path(binary tree)

Exit mobile version