0250. Count Univalue Subtrees

https://leetcode.com/problems/count-univalue-subtrees

Description

Given the root of a binary tree, return the number of uni-value subtrees.

A uni-value subtree means all nodes of the subtree have the same value.

Example 1:

**Input:** root = [5,1,5,5,5,null,5]
**Output:** 4

Example 2:

**Input:** root = []
**Output:** 0

Example 3:

**Input:** root = [5,5,5,5,5,null,5]
**Output:** 6

Constraints:

  • The numbrt of the node in the tree will be in the range [0, 1000].

  • -1000 <= Node.val <= 1000

ac

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int cnt;

    public int countUnivalSubtrees(TreeNode root) {
        cnt = 0;
        helper(root);
        return cnt;
    }

    private boolean helper(TreeNode root) {
        // exit
        if (root == null) return true;
        if (root.left == null && root.right == null) {
            cnt++;
            return true;
        }

        // handle
        // subtree is uni-value?
        boolean left = helper(root.left);
        boolean right = helper(root.right);
        if (!left || !right) {
            return false;
        }

        // root value equals children value?
        int lval = root.left != null ? root.left.val : root.val;
        int rval = root.right != null ? root.right.val : root.val;
        if (root.val == lval && root.val == rval) {
            cnt++;
            return true;
        }

        // unequal, return false
        return false;
    }
}

Last updated

Was this helpful?