https://www.jianshu.com/p/814d65a9c404
self.ans = None ##self在类中定义的变量是全局变量
需要加self
1、方法自身间的回溯需要加self
class Solution:
def lowestCommonAncestor(self, root, p, q):
# Value of current node or parent node.
parent_val = root.val
# Value of p
p_val = p.val
# Value of q
q_val = q.val
# If both p and q are greater than parent
'''方法自身间的回溯也需要加self'''
if p_val > parent_val and q_val > parent_val:
return self.lowestCommonAncestor(root.right, p, q)
# If both p and q are lesser than parent
elif p_val < parent_val and q_val < parent_val:
return self.lowestCommonAncestor(root.left, p, q)
# We have found the split point, i.e. the LCA node.
else:
return root
self.lowestCommonAncestor就是方法自身的回溯
2、同一个类,不同对象间的互相调用回溯需要加self
class Solution2:
def lowestCommonAncestor(self, root, p, q) :
self.res = None
self.dfs(root, p, q)
return self.res
'''同一个类,不同对象间的互相调用回溯需要加self'''
def dfs(self, root, p, q):
if not root: return 0
left = self.dfs(root.left, p, q)
right = self.dfs(root.right,p ,q)
mid = root == p or root == q
if left + right + mid > 1: self.res = root
return left or right or mid
lowestCommonAncestor方法中调用了dfs方法进行回溯
dfs方法中也调用了自身的回溯
不需要加self
1、方法内的函数递归自身不需要self
class Solution2:
def kthSmallest(self, root, k):
self.res, self.count = None, k ##建立两个全局变量res和count,分别用于存储答案与计数
'''方法内的函数递归自身不需要self'''
def inorder(root):
if not root: return
inorder(root.left)
if self.res: return ##每次判断res是否为空,若不为空直接返回
self.count -= 1
if not self.count: self.res = root.val
inorder(root.right)
inorder(root)
return self.res
inorder函数在自身回溯调用多次