-
Notifications
You must be signed in to change notification settings - Fork 0
Create 0103-binary-tree-zigzag-level-order-traversal.md #31
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
| - これは良さそう。O(n)の定数倍の最適化になる。 | ||
| - ところで、sequence.reverse()について調べていたところ、以下のように書いてあり興味深かったです。 | ||
| - > Reverse the items of sequence in place. This method maintains economy of space when reversing a large sequence. **To remind users that it operates by side-effect, it returns None.** | ||
| - https://docs.python.org/ja/3.13/library/stdtypes.html#sequence.reverse |
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.
sequence.reverse() の他に、built-in の reversed というのもありますね。
https://docs.python.org/3/library/functions.html#reversed
| ## Step 2 | ||
|
|
||
| - レビュー by GPT-5 | ||
| - > 反転自体は問題ありませんが、反転を避けたい場合は「収集中に `appendleft` を使う」手があります。具体的には偶数レベルでは `appendleft(node.val)`、奇数レベルでは `append(node.val)` として `deque` に詰め、最後に `list(...)` 化します。これは「コピー+反転」を避けられます。 |
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.
list にしているので結果的にコピーされていますよね……。
私は直感的にはこちらのほうが遅い気がします。(どうせそんなに問題になるレベルではないですが。)
| - https://github.com/garunitule/coding_practice/pull/27 | ||
| - > 当時はどちらかというとreverseするための計算量O(N)を節約できるからdequeよさそう、と思っていたのですが、今改めて考えると、おっしゃる通り結局listに変換する際にコピーをするのでその分結局O(N)発生してしまっていて、あまりdequeにすることの旨みはなかったかもしれません。。 | ||
| - よく考えてみると、reverseの有無によらずlist()でO(N)の計算が入るので、逆に遅くなるまでありそう。 | ||
| - 例えばリストで頑張るなら、最初にそのレベルの全ノードのプレイスホルダーを作っておいて、zigzagする場合は後ろからインデックスアクセスで詰めていけば若干速いかもしれない。 |
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.
Python の高速化はあまりというところがあります。
Python を使っている時点で C などから50-100倍くらい遅いので、ネイティブコードで書かれた関数をどう呼ぶかという勝負になってきます。numpy など。
本当に速度が必要だと C を使って拡張モジュールを作ることもできます。
https://docs.python.org/3/extending/extending.html
| if is_left_to_right: | ||
| index = i | ||
| else: | ||
| index = len(level_nodes) - 1 - i |
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.
Python はマイナスで後ろからアクセスしてくれるので、-1 - i でいいですかね?
この問題:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
次の問題:https://leetcode.com/problems/validate-binary-search-tree/