250. Count Univalue Subtrees

Leetcode

https://leetcode.com/problems/count-univalue-subtrees/arrow-up-right

題目

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

what is univalue ?

If the node meets one of the following criteria:

  1. The node has no children (base case)

  2. All of the node's children are univalue subtrees, and the node and its children all have the same value

解答

  • 方法一

Runtime: 117 ms, faster than 20.31% of JavaScript online submissions for Count Univalue Subtrees.

Memory Usage: 45.3 MB, less than 7.08% of JavaScript online submissions for Count Univalue Subtrees.

  • 方法二

Runtime: 72 ms, faster than 90.15% of JavaScript online submissions for Count Univalue Subtrees.

Memory Usage: 44.9 MB, less than 24.00% of JavaScript online submissions for Count Univalue Subtrees.

Last updated