1. 程式人生 > >[Swift Weekly Contest 117]LeetCode965. 單值二叉樹 | Univalued Binary Tree

[Swift Weekly Contest 117]LeetCode965. 單值二叉樹 | Univalued Binary Tree

ber false sset ever public oot note -i tree

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:

  1. The number of nodes in the given tree will be in the range [1, 100]
    .
  2. 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. 給定樹中的節點數將在範圍[1,100]內。
  2. 每個節點的值將是一個範圍[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 }

[Swift Weekly Contest 117]LeetCode965. 單值二叉樹 | Univalued Binary Tree