272. Closest Binary Search Tree Value II
解法1,最简单粗暴的办法,inorder, sort,取前k,竟然也AC了
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
res = []
self.inorder(root, res)
res = sorted(res, key=lambda x: abs(x-target))
return res[:k]
def inorder(self, root, res):
if not root:
return
self.inorder(root.left, res)
res.append(root.val)
self.inorder(root.right, res)
解法2,这个解法利用了tree的iterator的思想,很值得去多练习几次
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
ret = []
succ = []
pred = []
self.initializePredecessorStack(root, target, pred)
self.initializeSuccessorStack(root, target, succ)
if succ and pred and succ[-1].val == pred[-1].val:
self.getNextPredecessor(pred)
while k > 0:
if not succ:
ret.append(self.getNextPredecessor(pred))
elif not pred:
ret.append(self.getNextSuccessor(succ))
else:
succ_diff = abs(succ[-1].val - target)
pred_diff = abs(pred[-1].val - target)
if succ_diff < pred_diff :
ret.append(self.getNextSuccessor(succ));
else:
ret.append(self.getNextPredecessor(pred));
k -= 1
return ret
def initializeSuccessorStack(self, root, target, succ):
while root:
if root.val == target:
succ.append(root)
break
elif root.val > target:
succ.append(root)
root = root.left
else:
root = root.right
def initializePredecessorStack(self, root, target, pred):
while root:
if root.val == target:
pred.append(root)
break
elif root.val < target:
pred.append(root)
root = root.right
else:
root = root.left
def getNextSuccessor(self, succ):
curr = succ.pop()
ret = curr.val
curr = curr.right
while curr:
succ.append(curr)
curr = curr.left
return ret
def getNextPredecessor(self, pred):
curr = pred.pop()
ret = curr.val
curr = curr.left
while curr:
pred.append(curr)
curr = curr.right
return ret