func countUnivalSubtrees(_ root: TreeNode?) -> Int {
if root == nil {
return 0
}
if root?.left == nil && root?.right == nil {
return 1
}
var count = countUnivalSubtrees(root?.left) + countUnivalSubtrees(root?.right)
if isUnival(root?.left, root!.val) && isUnival(root?.right, root!.val) {
count += 1
}
return count
}
private func isUnival(_ node: TreeNode?, _ val: Int) -> Bool {
if node == nil {
return true
}
if node!.val != val {
return false
}
return isUnival(node?.left, val) && isUnival(node?.right, val)
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme