-
Notifications
You must be signed in to change notification settings - Fork 0
Maximum Depth of Binary Tree.md #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
まあ良いと思います。もう少し選択肢の幅があっても良いかなと思います。DFSで解いたり、再帰で解いてみたり。
if node is None: | ||
continue | ||
max_depth = depth | ||
node_and_depth_queue.append((node.left, depth + 1)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
自分はnode.leftがNoneならqueueに追加しないかなと思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ここは、入る前にチェックと出る前にチェックがあって、入る前にチェックするならば、はじめに root もチェックしないといけませんね。
入る前にチェックするならばチェックが3箇所に散るので関数にするのも一つです。
class Solution: | ||
def maxDepth(self, root: Optional[TreeNode]) -> int: | ||
max_depth = 0 | ||
node_and_depth_queue = deque([(root, 1)]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
queueを使うかlistを2つ使うかも好みですかね。自分はlistを2つ使う派です。
こんな感じ。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
nodes = [root]
depth = 0
while nodes:
depth += 1
next_nodes = []
for node in nodes:
if node.left:
next_nodes.append(node.left)
if node.right:
next_nodes.append(node.right)
nodes = next_nodes
return depth
見ました。いいと思います |
- ループ/再帰関数 | ||
- stackにdepthも入れる/階層ごとに二重ループを回す | ||
- > 階層ごとにしたいときには、私は List 2つで作るのが好みです。 | ||
- https://github.com/tarinaihitori/leetcode/pull/21/files#r1859073373 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://discord.com/channels/1084280443945353267/1201211204547383386/1219179255615717399
一つの変数に、2つの違う種類のものを入れておいて、その境界を個数で管理している
データの整合性が取れているということは、読んでいる人からすると全部読み終わらないと分からない
こういう理由なので、BFS の書き方として、深さをペアとしていれるのも分かりやすいと思います。
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/