java: add «2415. Reverse Odd Levels of Binary Tree»
URL: https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/
This commit is contained in:
parent
f0aa77436b
commit
f6084d4af5
1 changed files with 39 additions and 0 deletions
39
java/reverse-odd-levels-of-binary-tree.java
Normal file
39
java/reverse-odd-levels-of-binary-tree.java
Normal file
|
@ -0,0 +1,39 @@
|
|||
class Solution {
|
||||
private void traverse(ArrayList<ArrayList<TreeNode>> nodes, int level, TreeNode node) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (level % 2 == 1) {
|
||||
var idx = level >> 1;
|
||||
while (nodes.size() <= idx) {
|
||||
nodes.addLast(new ArrayList<TreeNode>());
|
||||
}
|
||||
|
||||
nodes.get(idx).addLast(node);
|
||||
}
|
||||
|
||||
traverse(nodes, level + 1, node.left);
|
||||
traverse(nodes, level + 1, node.right);
|
||||
}
|
||||
|
||||
private void reverse(ArrayList<TreeNode> level) {
|
||||
int i, j;
|
||||
for (i = 0, j = level.size() - 1; i < j; ++i, --j) {
|
||||
var tmp = level.get(i).val;
|
||||
level.get(i).val = level.get(j).val;
|
||||
level.get(j).val = tmp;
|
||||
}
|
||||
}
|
||||
|
||||
public TreeNode reverseOddLevels(TreeNode root) {
|
||||
var nodes = new ArrayList<ArrayList<TreeNode>>();
|
||||
traverse(nodes, 0, root);
|
||||
|
||||
for (var level : nodes) {
|
||||
reverse(level);
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue