★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10214859.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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
.
给定一个二叉树,计算单值子树的数目。
单值子树意味着子树的所有节点都具有相同的值。
例如:
给定二叉树,
5 / \ 1 5 / \ \ 5 5 5
返回4。
1 public class TreeNode { 2 public var val: Int 3 public var left: TreeNode? 4 public var right: TreeNode? 5 public init(_ val: Int) { 6 self.val = val 7 self.left = nil 8 self.right = nil 9 } 10 } 11 12 class Solution { 13 func countUnivalSubtrees(_ root:TreeNode?) -> Int { 14 var b:Bool = true 15 return isUnival(root, &b) 16 } 17 18 func isUnival(_ root:TreeNode?,_ b:inout Bool) -> Int 19 { 20 if root == nil { return 0 } 21 var l:Bool = true 22 var r:Bool = true 23 var res:Int = isUnival(root?.left, &l) + isUnival(root?.right, &r) 24 b = l && r 25 if root?.left != nil 26 { 27 b = b && (root!.val == root!.left!.val) 28 } 29 else 30 { 31 b = b && true 32 } 33 34 if root?.right != nil 35 { 36 b = b && (root!.val == root!.right!.val) 37 } 38 else 39 { 40 b = b && true 41 } 42 var num:Int = b ? 1 : 0 43 return res + num 44 } 45 }