题目来源:
自我感觉难度/真实难度:
题意:
分析:
自己的代码:
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 True return False def InOrder(self,root): if not root: return res=[]
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 True return False def 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 True s.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,不然没保存到内容