
Photo by
masaru12
ほぼ日刊競プロ leetcode 104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
考えたこと
根のノードから一番深い葉のノードまでの深さを出力する.
これも単純そうだが,一発で上手くいかず.以下を参考にした.
再帰的に深さを辿っていく,ノードがnullでない場合は再帰的に左側と右側を探索する.nullじゃない場合は1を足して返す.左右に対して行っていき右と左のより深い方をmax関数で最大値として返す.
ノードがnullの場合は0を返す.
# Definition for a binary tree node.
# 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:
def help(root):
d1 = 0
d2 = 0
if root is not None:
d1 = help(root.left)
d2 = help(root.right)
return 1+max(d1,d2)
else:
return 0
return help(root)