Advertisement
Alexxik

Untitled

Mar 17th, 2024
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.57 KB | None | 0 0
  1. // MARK: - Minimum Depth of Binary Tree
  2.  
  3. func minDepth(_ root: TreeNode?) -> Int {
  4.     if root == nil {
  5.         return 0
  6.     }
  7.    
  8.     if root?.left != nil && root?.right != nil {
  9.         return min(minDepth(root?.left), minDepth(root?.right)) + 1
  10.     }
  11.    
  12.     if root?.left != nil {
  13.         return minDepth(root?.left) + 1
  14.     }
  15.    
  16.     return minDepth(root?.right) + 1
  17. }
  18.  
  19.  
  20.  
  21.  
  22. let root = TreeNode(2)
  23. root.right = TreeNode(3)
  24. root.right?.right = TreeNode(4)
  25. root.right?.right?.right = TreeNode(5)
  26. root.right?.right?.right?.right = TreeNode(6)
  27.  
  28. minDepth(root)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement