102. Binary Tree Level Order Traversal#29
Conversation
| if (root == null) { | ||
| return values; | ||
| } | ||
| Queue<TreeNode> nodes = new ArrayDeque<>(); |
There was a problem hiding this comment.
頭から尻尾まで舐めることしかしていないので、ArrayList でもいいかなと思いました。
| if (node == null) { | ||
| return; | ||
| } | ||
| if (values.size() == level) { |
There was a problem hiding this comment.
上からしか呼ばないので、大きさが飛ばされることはないので、これでもいいですが、
while にするとアクセスする前にかならず、values.get(level) が存在するようになることが局所的に分かっていいかもしれません。
There was a problem hiding this comment.
There was a problem hiding this comment.
ありがとうございます!たしかにwhileだとより明示的ですね
| while (!nodes.isEmpty()) { | ||
| Queue<TreeNode> nodesInNextLevel = new ArrayDeque<>(); | ||
| List<Integer> valuesInNextLevel = new ArrayList<>(); | ||
| while (!nodes.isEmpty()) { |
There was a problem hiding this comment.
初見で同じwhile()が2個あって、意図を区別するまでに戸惑いがありました。
2個目の方はforで取り出すと、いいかもです。
There was a problem hiding this comment.
ありがとうございます!そのじてんでのQueueのsizeでやる感じですかね
| List<Integer> list = values.get(level); | ||
| list.add(node.val); |
There was a problem hiding this comment.
深さごとの部屋に追加していく操作は、こちらの解法でもありました。参考までに共有です。
t0hsumi/leetcode#26
| List<Integer> valuesInNextLevel = new ArrayList<>(); | ||
| while (!nodes.isEmpty()) { | ||
| TreeNode current = nodes.poll(); | ||
| valuesInNextLevel.add(current.val); |
There was a problem hiding this comment.
valuesInCurrentLevel の気がしました。
There was a problem hiding this comment.
ありがとうございます!つぎの階層での探索になるのでNextかなと思っていたのですが認識相違ありますでしょうか?
| values.add(new ArrayList<>()); | ||
| } | ||
| List<Integer> list = values.get(level); | ||
| list.add(node.val); |
There was a problem hiding this comment.
javaのListが参照渡しなのでこのような書き方をしても動くと思うのですが、ぱっと見valuesの中身に変更が生じていることがわかりにくいので、values[level].add(node.val);と書いてもいいと思いました。listはこの2行でしか使われていないのであえて宣言する必要もそんなにないとも思いました。
問題URL:https://leetcode.com/problems/binary-tree-level-order-traversal/description/