LeetCode / Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
return its depth = 3.
再びバイナリツリーを扱った問題で、最も階層の深いところの木の深さを返します。
個人的にはNoteに'Find one line solution.'と付け加えてみたい。難しくない問題ですが、one lineで書けるとドヤ顔決めたくなりますね。
解答・解説
解法1
One line solutionです。自分で思いつけると気持ち良いですね。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) if root else 0
「もし木が存在していれば1+(左右の木のうち、より深い木の深さ)を返し、木が存在しなければ0を返す」関数を定義し、recursiveをとってやれば完成です。
解法2
もちろんIterativeな解法もあります。可読性は落ちますが、複雑ではないですし、計算時間も解法1に見劣りしません。
class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ depth = 0 l = [root] if root else [] while l: depth += 1 l_tmp =[] for t in l: if t.left: l_tmp.append(t.left) if t.right: l_tmp.append(t.right) l = l_tmp return depth
deque型を使っても書けますが、今回は要素を取り出す操作はなくループを回すだけなので、deque型をわざわざ使うメリットはありません。