A binary tree is univalued if every node in the tree has the same value.
Return true
if and only if the given tree is univalued.
Example 1:
Input: [1,1,1,1,1,null,1] Output: true
Example 2:
Input: [2,2,2,5,2] Output: false
Note:
- The number of nodes in the given tree will be in the range
[1, 100]
. - Each node‘s value will be an integer in the range
[0, 99]
.
如果二叉树中的每个节点都具有相同的值,则二叉树是单值的。
如果且仅当给定树为单值时返回true。
例1:
输入:[1,1,1,1,1,null,1]
输出:真
例2:
输入:[2,2,2,5,2]
输出:假
注:
- 给定树中的节点数将在范围[1,100]内。
- 每个节点的值将是一个范围[0,99]内的整数。
12 ms
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 var s:Set<Int> = Set<Int>() 16 func isUnivalTree(_ root: TreeNode?) -> Bool { 17 s.insert(root!.val) 18 if root?.left != nil 19 { 20 isUnivalTree(root!.left) 21 } 22 if root?.right != nil 23 { 24 isUnivalTree(root!.right) 25 } 26 return s.count == 1 27 } 28 }
原文地址:https://www.cnblogs.com/strengthen/p/10201416.html
时间: 2024-10-08 16:33:44