# LeetCode Easy 104. Maximum Depth of Binary Tree
tags: leetcode
問題
二分木を与えられた時, 最大深度を見つけろ
最大震度は根から最も遠い葉までの最長の通り方で通るノードの数である
注意
葉は子のいないノードである
解法(recursive)
- 基底は葉(このいないノード)で, たどり着いたときの深さを返せば良いです
- 葉で関数を実行した場合, 深さは$0$です
- 再帰的には
現在までの最大深度 + 1
を返せば良いです左部分木の深さ + 右部分木の深さ + 1
を返します
計算量
木の深さを$n$とします
- 空間計算量
- 木の深さ$n$なので$O(n)$です
- 時間計算量
- ノードを全て遡ります
- ノードの数の最大値は$2^{n}$なので$O(2^{n})$
Python
# 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: if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode* root) { if (!root) { return 0; } return max(maxDepth(root->left), maxDepth(root->right)) + 1; } };
ちなみに
これはDepth First Searchであり, Stackを使えばiterativeにも解けます
暇な人は解いてみましょう(私はテストなのでパス)