Python實現"二叉樹的最大深度"的兩種方法
阿新 • • 發佈:2019-02-14
給定一棵二叉樹,返回它的最大深度
最大深度是指樹中最長路徑所擁有的結點數量
注意:葉子節點沒有子節點
例如:
給定二叉樹[3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
它的返回值為3
def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 curLevelNodeList = [root] length = 0 while curLevelNodeList: tempNodeList = [] for node in curLevelNodeList: if node.left is not None: tempNodeList.append(node.left) if node.right is not None: tempNodeList.append(node.right) curLevelNodeList = tempNodeList length += 1 return length
2:遞迴,比較每一條路徑的長短
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left = self.maxDepth(root.left)+1
right = self.maxDepth(root.right)+1
return max(left, right)