Leetcode 0250: Count Univalue Subtrees

题目描述:

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 = [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

Time complexity: O(n)
Space complexity : O(H)
DFS:
同值子树的两种情况:

  1. 此树没有叶子结点
  2. 所有的叶子结点的值是同值子树而且所有的节点值都相同
/**
 * 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 {
    
    
    int count;
    public int countUnivalSubtrees(TreeNode root) {
    
    
        count = 0;
        helper(root);
        return count;
    }
    
    boolean helper(TreeNode root) {
    
    
        if(root == null) return true;
        boolean left = helper(root.left);
        boolean right = helper(root.right);
        if(left && right && 
           (root.left == null || root.val == root.left.val) && 
           (root.right == null || root.val == root.right.val)){
    
    
            count++;
            return true;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113883180