GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/tree/bst/bst_closest_value.py at master · RajaRamu/algorithms Expand file tree/ Copy pathbst_closest_value.pyMore file actions 28 lines (24 loc) · 737 Bytes / Copy pathbst_closest_value.pyFile metadata and controls28 lines (24 loc) · 737 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 # Given a non-empty binary search tree and a target value, # find the value in the BST that is closest to the target. # Note: # Given target value is a floating point. # You are guaranteed to have only one unique value in the BST # that is closest to the target. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None def closest_value(root, target): """ :type root: TreeNode :type target: float :rtype: int """ a = root.val kid = root.left if target < a else root.right if not kid: return a b = closest_value(kid, target) return min((a,b), key=lambda x: abs(target-x)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |