class Solution(): def closestValue(self, root, target): if root == None: return None if target <= root.val: if root.left != None: closestValue_left = self.closestValue(root.left, target) if root.val - target < abs(closestValue_left - target): return root.val else: return closestValue_left else: return root.val else: if root.right != None: closestValue_right = self.closestValue(root.right, target) if root.val - target < abs(closestValue_right - target): return root.val else: return closestValue_right else: return root.val def closestValue2(self, root, target): if root == None: return None ans = abs(root.val - target) ans_val = root.val while True: if abs(root.val - target) < ans: ans = abs(root.val - target) ans_val = root.val if target < root.val and root.left: root = root.left elif target > root.val and root.right: root = root.right else: break return ans_val
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question