"if right and left: return root" 和 "return right or left" 如何帮助我们找到最不共同的祖先?
How does "if right and left: return root" and the "return right or left" help us find the least common ancestor?
class TreeNode:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def insert(temp,data):
que = []
que.append(temp)
while (len(que)):
temp = que[0]
que.pop(0)
if (not temp.left):
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
que.append(temp.left)
if (not temp.right):
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
que.append(temp.right)
def make_tree(elements):
Tree = TreeNode(elements[0])
for element in elements[1:]:
insert(Tree, element)
return Tree
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
if not root:
return None
if root.data == p or root.data ==q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
**if right and left:
return root**
*return right or left*
ob1 = Solution()
tree = make_tree([3,5,1,6,2,0,8,None,None,7,4])
print(ob1.lowestCommonAncestor(tree, 5, 1).data)
当我们想要 return 单个节点而不是两个节点时,为什么我们 return 向右或向左?
我意识到布尔值“左右”return即使左右不是同一个树节点也是如此。此外,没有编写比较功能。有必要吗?
return right or left
returnsright
如果不是None
,否则检查left
和returnsleft
,如果不是 None
。如果left
和right
都是None
returnsNone
。因此,仅返回一个节点或 None
。
只有当 left
和 right
都不是 None
时,if right and left
才是 True
class TreeNode:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def insert(temp,data):
que = []
que.append(temp)
while (len(que)):
temp = que[0]
que.pop(0)
if (not temp.left):
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
que.append(temp.left)
if (not temp.right):
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
que.append(temp.right)
def make_tree(elements):
Tree = TreeNode(elements[0])
for element in elements[1:]:
insert(Tree, element)
return Tree
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
if not root:
return None
if root.data == p or root.data ==q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
**if right and left:
return root**
*return right or left*
ob1 = Solution()
tree = make_tree([3,5,1,6,2,0,8,None,None,7,4])
print(ob1.lowestCommonAncestor(tree, 5, 1).data)
当我们想要 return 单个节点而不是两个节点时,为什么我们 return 向右或向左?
我意识到布尔值“左右”return即使左右不是同一个树节点也是如此。此外,没有编写比较功能。有必要吗?
return right or left
returnsright
如果不是None
,否则检查left
和returnsleft
,如果不是 None
。如果left
和right
都是None
returnsNone
。因此,仅返回一个节点或 None
。
left
和 right
都不是 None
时,if right and left
才是 True