FastPrepCount Uni-Valued Subtrees
Problems/Count Uni-Valued Subtrees

Count Uni-Valued Subtrees

Amazon logoAmazon● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: Reported in an Amazon SDE2 interview list as counting uni-valued subtrees. The source does not specify a tree encoding, empty-tree behavior, or bounds; this practice version uses a nullable level-order tree, returns zero for an empty tree, and caps trees at 500 nodes with values from -1,000 through 1,000. Problem match confidence: approximately 99%.

Given the root of a binary tree, return the number of subtrees whose nodes all have the same value.

Every node defines one subtree consisting of that node and all of its descendants. A leaf is therefore always a uni-valued subtree.

Function

countUnivalSubtrees(root: TreeNode) → int

Examples

Example 1

root = [5,1,5,5,5,null,5]return = 4

The three leaf fives and the right subtree rooted at five are uni-valued.

Example 2

root = [1]return = 1

A leaf is uni-valued.

Example 3

root = []return = 0

An empty tree contains no subtree.

Constraints

  • The tree contains between 0 and 500 nodes.
  • -1000 ≤ Node.val ≤ 1000.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        // write your code here
    }
}
Checking account…