Advertisement
HXXXXJ

222. Count Complete Tree Nodes

Apr 13th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.93 KB | None | 0 0
  1.     func countNodes(_ root: TreeNode?) -> Int {
  2.         guard let root = root else { return 0}
  3.        
  4.         let leftH = heightLeft(root.left)
  5.         let rightH = heightRight(root.right)
  6.  
  7.         if leftH == rightH {
  8.             if leftH == 0 { return 1}
  9.             return Int(pow(2.0, Double(leftH + 1))) - 1
  10.         }
  11.         return countNodes(root.left) + countNodes(root.right) + 1
  12.     }
  13.    
  14.     func heightLeft(_ root: TreeNode?) -> Int{
  15.         guard let root = root else {return 0}
  16.         var h = 1
  17.         var runner = root
  18.         while runner.left != nil{
  19.             runner = runner.left!
  20.             h += 1
  21.         }
  22.         return h
  23.     }
  24.     func heightRight(_ root: TreeNode?) -> Int{
  25.         guard let root = root else {return 0}
  26.         var h = 1
  27.         var runner = root
  28.         while runner.right != nil{
  29.             runner = runner.right!
  30.             h += 1
  31.         }
  32.         return h
  33.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement