Advertisement
jinhuang1102

700. Search in a Binary Search Tree

Mar 13th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. """
  2. 用Iteration的方法来求出sorted array, 然后用binary search去找到值
  3. """
  4.  
  5. class Solution(object):
  6.     def inorder(self, root, ls):
  7.         st = []
  8.         while st or root:
  9.             if root:
  10.                 st.append(root)
  11.                 root = root.left
  12.             else:
  13.                 root = st.pop()
  14.                 ls.append(root)
  15.                 root = root.right    
  16.    
  17.     def searchBST(self, root, val):
  18.         """
  19.        :type root: TreeNode
  20.        :type val: int
  21.        :rtype: TreeNode
  22.        """
  23.         ls = []
  24.         self.inorder(root, ls)
  25.        
  26.         l = 0
  27.         r = len(ls)-1
  28.         while l <= r:
  29.             mid = l + (r - l) // 2
  30.             if val < ls[mid].val:
  31.                 r = mid - 1
  32.             elif val == ls[mid].val:
  33.                 return ls[mid]
  34.             else:
  35.                 l = mid + 1
  36.          
  37.         return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement