Advertisement
halaluddin

Day14-Apr-Search_in_a_BST-Iterative

Apr 14th, 2022
1,258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.84 KB | None | 0 0
  1. class Solution {
  2.    
  3.     /*
  4.         Problem Link: https://leetcode.com/problems/search-in-a-binary-search-tree/
  5.         Language:
  6.             Swift
  7.         Params:
  8.             root: Custom(TreeNode) data(class) type;
  9.             val: Int;
  10.         Return:
  11.             Custom(TreeNode) data(class) type; return a TreeNode object.
  12.         Complexity analysis:
  13.             Space: Constant space
  14.             Time: O(log n)
  15.     */
  16.    
  17.     func searchBST(_ root: TreeNode?, _ val: Int) -> TreeNode? {
  18.         var curr_node = root
  19.         while curr_node != nil {
  20.             if curr_node?.val == val {
  21.                 return curr_node
  22.             }
  23.             if curr_node!.val >= val {
  24.                 curr_node = curr_node?.left
  25.             } else {
  26.                 curr_node = curr_node?.right
  27.             }
  28.         }
  29.         return nil
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement