本文主要是介绍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 = Noneclass Solution(object):def __init__(self):self.count = 0def countUnivalSubtrees(self, root):""":type root: TreeNode:rtype: int"""self.unival(root)return self.countdef unival(self, root):if root == None:return True if root.left == None and root.right == None:self.count += 1return Trueleft = 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 += 1return Trueelse:return False
这篇关于LeetCode 题解(265) : Count Univalue Subtrees的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!