Count Univalue Subtrees

update Sep,1 2017 19:28

LeetCodearrow-up-right

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

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

For example:

          Given binary tree,
                        5
                       / \
                      1   5
                     / \   \
                    5   5   5
          return 4.

Basic Idea:

使用分治的思路,维持一个 int count 全局变量,写一个 boolean helper(TreeNode root),实现:

  • 如果当前root的tree符合要求,返回True,count++;

  • 如果当前root的左右两子树都返回True,并且左右child的值为null或和root相同,则说明当前root所在树符合要求;

利用这个思路,可以轻松写出recursive function;

Python Code:

注意判断逻辑,这道题中排除不符合条件的情况比较简便;

如果列举满足条件的情况,见下方python code,注意对比: