Sum of all Left Leaves in Java | Tree Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a binary tree, find out the sum of all left leaves value.

Example 

Sum of all left leaves

There are two left leaves in above binary tree, 9 and 15, So result should be 24.

Algorithm 

We can use Depth First Traversal algorithm to solve this problem.

Program 


public class DFS {

	public static void main(String[] args) {
		
		DFS dfs = new DFS();
		
		TreeNode root = new TreeNode(3);
		root.left = new TreeNode(9);
		root.right = new TreeNode(20);		
		root.right.left = new TreeNode(15);
		root.right.right = new TreeNode(7);
		
		int result = dfs.sumOfAllLeftLeaves(root);
		System.out.println(result);
	}
	
	public int sumOfAllLeftLeaves(TreeNode root) {
        return dfs(root, false, 0);
    }

	public int dfs(TreeNode node, boolean isLeft, int sum){
        
        if(node == null) {
        	return sum;
        }
        
        if(node.left == null && node.right == null && isLeft){
            sum = sum + node.val;
            return sum;
        }
        
        sum = dfs(node.left, true, sum);
        sum = dfs(node.right, false, sum);
        return sum;
    }
	
	public static class TreeNode {		
		int val;
		TreeNode left;
		TreeNode right;
		
		TreeNode(int x) {
			val = x;
		}
	}
}

Result

24

Similar Post

  1. Sum of all Left Leaves
  2. Level Order Traversal of Binary Tree
  3. Minimum Distance Between BST Nodes

That’s all for Sum of all Left Leaves in Java, If you liked it, please share your thoughts in a comments section and share it with others too.