【Arai60】21問目 104_Maximum Depth of Binary Tree#21
Merged
shining-ai merged 2 commits intomainfrom Jun 30, 2024
Merged
Conversation
nodchip
reviewed
Mar 8, 2024
| class Solution: | ||
| def maxDepth(self, root: Optional[TreeNode]) -> int: | ||
|
|
||
| def search_max_depth(node): |
There was a problem hiding this comment.
補助関数に分けても良いと思いますし、 maxDepth() と引数が同じため、 maxDepth() を直接再帰呼び出ししても良いと思いました。
Owner
Author
There was a problem hiding this comment.
補助関数なしでできましたね。
rootがない時の戻り値がすぐ分かって、少し分かりやすくなると思いました。
hayashi-ay
reviewed
Mar 8, 2024
| def search_max_depth(node): | ||
| if not node: | ||
| return 0 | ||
| left_depth = search_max_depth(node.left) + 1 |
There was a problem hiding this comment.
left_depthという命名だと1足さないものな気がするんですよね。
left_depth = search_max_depth(node.left)
Owner
Author
There was a problem hiding this comment.
深さだとrootが0カウントになってしまうということですね。
| node_depth_queue.append((node.left, depth + 1)) | ||
| if node.right: | ||
| node_depth_queue.append((node.right, depth + 1)) | ||
| max_depth = max(max_depth, depth) |
There was a problem hiding this comment.
BFSなのでmax取らなくても良いですね。
Suggested change
| max_depth = max(max_depth, depth) | |
| max_depth = depth |
Owner
Author
There was a problem hiding this comment.
一番最後のdepthが最大値で決まってますね。
max_depth変数作らずにdepthを返しても動きますね。
| max_depth = 1 | ||
| while stack_node_depth: | ||
| node, depth = stack_node_depth.pop() | ||
| if node.left: |
There was a problem hiding this comment.
好みの問題ですが、DFSの探索をするときは左側から見ていくのが自然な気がします。そうなるとstackに積む順番はnode.right, node.leftの順になります。
| @@ -0,0 +1,12 @@ | |||
| class Solution: | |||
| def maxDepth(self, root: Optional[TreeNode]) -> int: | |||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
問題
https://leetcode.com/problems/maximum-depth-of-binary-tree/