LeetCode 题解(265) : Count Univalue Subtrees

来源:互联网 发布:淘宝卖的印度威格拉 编辑:程序博客网 时间:2024/06/04 18:33

题目:

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

0 0
原创粉丝点击