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)
当我们想要返回单个节点而不是两个节点时,为什么我们要返回右侧或左侧?
我意识到布尔值"右和左"返回 true,即使右和左不是同一个 TreeNode。此外,没有编写比较函数。有必要吗?
> 如果不None
return right or left
则返回right
,否则,它检查left
并返回left
,如果它不是None
。如果left
和right
都None
则返回None
。因此,只返回一个节点或None
。
只有当left
和right
都不是None
时,if right and left
才会True