Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func countNodes(_ root: TreeNode?) -> Int {
- guard let root = root else { return 0}
- let leftH = heightLeft(root.left)
- let rightH = heightRight(root.right)
- if leftH == rightH {
- if leftH == 0 { return 1}
- return Int(pow(2.0, Double(leftH + 1))) - 1
- }
- return countNodes(root.left) + countNodes(root.right) + 1
- }
- func heightLeft(_ root: TreeNode?) -> Int{
- guard let root = root else {return 0}
- var h = 1
- var runner = root
- while runner.left != nil{
- runner = runner.left!
- h += 1
- }
- return h
- }
- func heightRight(_ root: TreeNode?) -> Int{
- guard let root = root else {return 0}
- var h = 1
- var runner = root
- while runner.right != nil{
- runner = runner.right!
- h += 1
- }
- return h
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement