題目來源:
?
自我感覺難度/真實難度:
?
題意:
?
分析:
?
自己的代碼:
class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""All=self.InOrder(root)Plus=[]#for i in range(All.size()):for i in range(len(All)):for j in range(len(All)):Plus.append(All[i]+All[j])if k in Plus:return Truereturn Falsedef InOrder(self,root):if not root:returnres=[]
res.append(root.val)
self.InOrder(root.left)
self.InOrder(root.right) return res
1.中序遍歷不會,這不是中序遍歷
2.這樣沒有得到中序遍歷
?
代碼效率/結果:
?
優秀代碼:
# 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 findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""res = self.inOrder(root)resset = set(res)for num in res:if k != 2 * num and k - num in resset:return Truereturn Falsedef inOrder(self, root):if not root:return []res = []res.extend(self.inOrder(root.left))res.append(root.val)res.extend(self.inOrder(root.right))return res
?
代碼效率/結果:
Runtime:?84 ms, faster than?56.86%?of?Python?online submissions for?Two Sum IV - Input is a BST.
?
優化后的代碼:
class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""bfs, s = [], set()bfs = [root]for i in bfs:if k - i.val in s:return Trues.add(i.val)if i.left:bfs.append(i.left)if i.right:bfs.append(i.right)return False
Runtime:?108 ms, faster than?33.56%?of?Python?online submissions for?Two Sum IV - Input is a BST.
這個時間測量是不是有問題呢?
反思改進策略:
1.使重復元素只有一個的辦法:set()
? ?2.中序的過程中,一定要res.extend,不然沒保存到內容