[LeetCode 250] Count Univalue Subtrees (medium)

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. (意思是,该subtree下所有节点都相同,所以第二层的1,和根节点的5不是 Uni-value subtree)

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

Output: 4

Solution: Bottom-Up recursion

  1. 从当前节点,拿到其left, right子节点是否是Uni-value subtree
  2. 再根据左右子树的信息,判断当前节点是否是Uni-value subtree
    • 如果任一一个不是, 那么当前节点就不是Uni-value subtree
    • 如果左右子树都是Uni-value subtree,再判断root.val == root.left.val ? && root.val == root.right.val

如果当前节点是Uni-value subtree,那么global_count ++

Note: 有一种情况需处理,即 current node 只有左子树或只有右子树,且current node val == 其某一子树的val, 这种情况当前节点也是Uni-value subtree

 if ((isLeftUnival && isRightUnival)
      && (root.left == null || root.left.val == root.val)
      && (root.right == null || root.right.val == root.val)) 
  1. 返回当前节点是否是 uni-value subtree
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int[] count = { 0 };
        countUnivalSubtrees (root, count);
        
        return count[0];
    }
    
    private boolean countUnivalSubtrees (TreeNode root, int[] count) {
        if (root == null) {
            return true;
        }
        
        boolean isLeftUnival = countUnivalSubtrees(root.left, count);
        boolean isRightUnival = countUnivalSubtrees(root.right, count);
        
        if ((isLeftUnival && isRightUnival)
            && (root.left == null || root.left.val == root.val)
            && (root.right == null || root.right.val == root.val)) {
            count [0]++;
            return true;  
        }

        return false;
    }
}

你可能感兴趣的:([LeetCode 250] Count Univalue Subtrees (medium))