LeetCode 题解(265) : Count Univalue Subtrees

题目:

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.

题解:

递归。

Java版:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        unival(root);
        return count;
    }
    
    private boolean unival(TreeNode root) {
        if(root == null)
            return true;
        if(root.left ==null && root.right == null) {
            count++;
            return true;
        }
        boolean left = unival(root.left);
        boolean right = unival(root.right);
        if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) {
            count++;
            return true;
        }
        return false;
    }
    
    private int count = 0;
}

Python版:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def __init__(self):
        self.count = 0
    
    def countUnivalSubtrees(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.unival(root)
        return self.count
        
    def unival(self, root):
        if root == None:
            return True 
        if root.left == None and root.right == None:
            self.count += 1
            return True
        left = self.unival(root.left)
        right = self.unival(root.right)
        if left and right and (root.left == None or root.left.val == root.val) and (root.right == None or root.right.val == root.val):
            self.count += 1
            return True
        else:
            return False

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值