Closed labuladong closed 1 year ago
# Aug 16
# Maximum Depth of a Tree
# There is either a recursive solution, or a traversal solution
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
return self.traverse(root, 0)
def traverse(self, root, n):
if not root:
return n
else:
return max(self.traverse(root.left, n+1), self.traverse(root.right, n+1))
class Solution:
def __init__(self,):
self.max = 0
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
self.traverse(root)
return self.max
def traverse(self, root):
if not root:
return
else:
left = self.depth(root.left)
right = self.depth(root.right)
self.max = max(self.max, left+right)
self.traverse(root.left)
self.traverse(root.right)
def depth(self, root):
if not root:
return 0
else:
return 1 + max(self.depth(root.left), self.depth(root.right))
本期打卡已结算完成。报名最新一期的打卡活动 点这里