[Swift]LeetCode250.計數相同值子樹的個數 $ Count Univalue Subtrees

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-hctfmhws-mb.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a binary tree, count the number of uni-value subtrees.node

A Uni-value subtree means all nodes of the subtree have the same value.git

For example:
Given binary tree,github

              5
             / \
            1   5
           / \   \
          5   5   5

return 4.微信


給定一個二叉樹,計算單值子樹的數目。spa

單值子樹意味着子樹的全部節點都具備相同的值。code

例如:htm

給定二叉樹,blog

              5
             / \
            1   5
           / \   \
          5   5   5

返回4。get


 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 }
相關文章
相關標籤/搜索