From f6084d4af5f159f013d36262a7f15262210b4879 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 20 Dec 2024 22:16:12 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB2415.=20Reverse=20Odd=20Lev?= =?UTF-8?q?els=20of=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/ --- java/reverse-odd-levels-of-binary-tree.java | 39 +++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 java/reverse-odd-levels-of-binary-tree.java diff --git a/java/reverse-odd-levels-of-binary-tree.java b/java/reverse-odd-levels-of-binary-tree.java new file mode 100644 index 0000000..da5519e --- /dev/null +++ b/java/reverse-odd-levels-of-binary-tree.java @@ -0,0 +1,39 @@ +class Solution { + private void traverse(ArrayList> 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()); + } + + nodes.get(idx).addLast(node); + } + + traverse(nodes, level + 1, node.left); + traverse(nodes, level + 1, node.right); + } + + private void reverse(ArrayList 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>(); + traverse(nodes, 0, root); + + for (var level : nodes) { + reverse(level); + } + + return root; + } +}