如何使用此处工作的 DFS 为最大深度编写此 python 代码?
How to this python code for max depth using DFS working here?
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
return root and 1 + max(max_depth(root.left), max_depth(root.right)) or 0
if __name__ =="__main__":
def build_tree(nodes):
val = next(nodes)
if not val or val == 'x': return
cur = Node(int(val))
cur.left = build_tree(nodes)
cur.right = build_tree(nodes)
return cur
root = build_tree(iter(input().split()))
print(max_depth(root))
这里给出了正确答案。但是我不明白 max_depth 函数在这里是如何工作的。更具体地说,这里是 'and' 和 'or' 操作。
and
用于检查根是否不是None
。所以就像这样做:
0 if root is None else 1 + max(max_depth(root.left), max_depth(root.right))
这个表达式:
root and 1 + max(max_depth(root.left), max_depth(root.right)) or 0
相当于:
1 + max(max_depth(root.left), max_depth(root.right)) if root else 0
这是因为 and
将 return 第一个操作数为假时,如果第一个为真则为第二个操作数。 or
操作数将 return 其第一个操作数为真时,其第二个操作数为假。
您还可以使用单独的 return
语句将其写得更详细:
if root:
return 1 + max(max_depth(root.left), max_depth(root.right))
else:
return 0
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
return root and 1 + max(max_depth(root.left), max_depth(root.right)) or 0
if __name__ =="__main__":
def build_tree(nodes):
val = next(nodes)
if not val or val == 'x': return
cur = Node(int(val))
cur.left = build_tree(nodes)
cur.right = build_tree(nodes)
return cur
root = build_tree(iter(input().split()))
print(max_depth(root))
这里给出了正确答案。但是我不明白 max_depth 函数在这里是如何工作的。更具体地说,这里是 'and' 和 'or' 操作。
and
用于检查根是否不是None
。所以就像这样做:
0 if root is None else 1 + max(max_depth(root.left), max_depth(root.right))
这个表达式:
root and 1 + max(max_depth(root.left), max_depth(root.right)) or 0
相当于:
1 + max(max_depth(root.left), max_depth(root.right)) if root else 0
这是因为 and
将 return 第一个操作数为假时,如果第一个为真则为第二个操作数。 or
操作数将 return 其第一个操作数为真时,其第二个操作数为假。
您还可以使用单独的 return
语句将其写得更详细:
if root:
return 1 + max(max_depth(root.left), max_depth(root.right))
else:
return 0