714274. Good Subtrees

Medium

Good Subtrees

Slug: good-subtrees--170647 Difficulty: Medium Id: 714274 Topic Tags: DFS, Algorithms Company Tags: None

Summary

Given a binary tree, find all good subtrees. A subtree is considered good if the sum of its node values is greater than or equal to the average value of the whole tree.

The problem requires us to traverse the tree using Depth-First Search (DFS) and calculate the sum of each subtree's node values.

Detailed Explanation

To solve this problem, we'll start by traversing the binary tree using DFS. We'll keep track of the sum of each subtree's node values and compare it with the average value of the whole tree.

Here's a step-by-step breakdown of the solution:

  1. Traverse the binary tree using DFS.
  2. For each node, calculate the sum of its left and right subtrees (if they exist).
  3. Calculate the total sum of all nodes in the current subtree.
  4. Compare the total sum with the average value of the whole tree. If it's greater than or equal to the average value, mark this subtree as a good subtree.

To calculate the average value of the whole tree, we'll first traverse the tree and count the number of nodes. Then, we'll divide the total sum by the number of nodes to get the average value.

Time complexity analysis:

  • Traversing the binary tree using DFS: O(n), where n is the number of nodes in the tree.
  • Calculating the sum of each subtree's node values: O(n) for each subtree, so overall time complexity is O(n^2).
  • Calculating the average value of the whole tree: O(n).

Space complexity analysis:

  • Recursive function calls during DFS traversal: O(h), where h is the height of the tree.
  • Additional space required to store intermediate results: O(1) extra space.

Optimized Solutions

Java

View on GeeksforGeeks
public class GoodSubtrees {
    public static List<TreeNode> findGoodSubtrees(TreeNode root) {
        List<TreeNode> goodSubtrees = new ArrayList<>();
        calculateGoodSubtrees(root, 0, null, goodSubtrees);
        return goodSubtrees;
    }

    private static void calculateGoodSubtrees(TreeNode node, int sum, TreeNode parent, List<TreeNode> goodSubtrees) {
        if (node == null) {
            return;
        }
        sum += node.val;
        boolean isGood = isGoodSum(sum, parent != null ? parent.val : 0);
        if (isGood) {
            goodSubtrees.add(node);
        }
        calculateGoodSubtrees(node.left, sum, node, goodSubtrees);
        calculateGoodSubtrees(node.right, sum, node, goodSubtrees);
    }

    private static boolean isGoodSum(int sum, int average) {
        return sum >= average;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.