Conversation
|
Level (同じ深さ) ごとに値を集めると考えると、BFSの方がDFSよりも素直な気がします。 |
103/sol1_bfs.py
Outdated
| if depth % 2 == 0: | ||
| res[depth].append(node.val) | ||
| else: | ||
| res[depth].insert(0, node.val) |
There was a problem hiding this comment.
list の先頭や途中に対して insert をすると、それより後の要素をひとつづつずらさなければならないため、 O(n) かかります。原則避けたほうが無難だと思います。要素数が十分に小さいのであれば問題ないかもしれません。
There was a problem hiding this comment.
なるほど、要素数が多い場合にはresをdequeのlistとして用意し、最後にlistのlistに変換した方が計算量が小さくなるかもしれません。
103/sol1_bfs.py
Outdated
| res: List[List[int]] = [] | ||
|
|
||
| def dfs(node: Optional[TreeNode], depth: int) -> None: |
There was a problem hiding this comment.
There was a problem hiding this comment.
「自分が読めればいい」の癖が抜けないので、注意します。
103/sol1_bfs.py
Outdated
| if len(res) == depth: | ||
| res.append([]) |
There was a problem hiding this comment.
別な問題に対するコメントですが、こちらにも共通しそうなので。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.hmkwp3k9djib
1段だけしか拡張しなくても例外が投げられることがないことに気がつくパズルを解かせる必要ないですよね。
103/sol1_bfs.py
Outdated
| dfs(node.left, depth + 1) | ||
| dfs(node.right, depth + 1) | ||
|
|
||
| dfs(root, 0) |
There was a problem hiding this comment.
rootのdepthは1であるのが自然に思いました(0-indexです、と言われればそうかあ、とも思いますが…)。
There was a problem hiding this comment.
うーん、ここは0のままにしようと思います。0-indexなら不自然ではないと思います。
103/sol1_bfs.py
Outdated
103/sol1_bfs.py
Outdated
| res: List[List[int]] = [] | ||
|
|
||
| def dfs(node: Optional[TreeNode], depth: int) -> None: |
There was a problem hiding this comment.
103/sol1_bfs.py
Outdated
|
|
||
| class Solution: | ||
| def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: | ||
| res: List[List[int]] = [] |
There was a problem hiding this comment.
Pythonだとレキシカルスコープで再帰を回せるので,関数のシグネチャが長くならず,便利ですね.
There was a problem hiding this comment.
確かC++とかは引数を渡す必要がありましたね。
余裕があったらPython以外の言語も学ぼうと思います。
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/