Skip to content

Instantly share code, notes, and snippets.

@greenchiu
Created December 10, 2019 08:39
Show Gist options
  • Save greenchiu/6c3bc45a82e8a5ca059019d2c356c6ca to your computer and use it in GitHub Desktop.
Save greenchiu/6c3bc45a82e8a5ca059019d2c356c6ca to your computer and use it in GitHub Desktop.
class UnivalCountSolution {
private var count = 0
private var testCount = 0
func soultion(_ root: TreeNode?) -> Int {
guard let root = root else {
return 0
}
isUnivalSubtree(root)
return count
}
private func isUnivalSubtree(_ node: TreeNode) -> Bool {
testCount += 1
print("total visit node", testCount)
if node.left == nil, node.right == nil {
count += 1
return true
}
var isUnival = true
if let left = node.left {
print("l", left.val)
isUnival = isUnival && node.val == left.val && isUnivalSubtree(left)
}
if let right = node.right {
// 這邊 isUnivalSubtree(right) 沒作用
print("r", right.val)
isUnival = isUnival && node.val == right.val && isUnivalSubtree(right)
}
if isUnival {
count += 1
}
return isUnival
}
}
let node = TreeNode(5)
node.left = TreeNode(1)
node.left?.left = TreeNode(5)
node.left?.right = TreeNode(5)
node.right = TreeNode(5)
node.right?.right = TreeNode(5)
UnivalCountSolution().soultion(node)
/* log
total visit node 1
l 1
r 5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment