← All problems

2415. Reverse Odd Levels of Binary Tree

MediumOpen on LeetCodeProblem statement

Problem Statement

2415. Reverse Odd Levels of Binary Tree

Medium


Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.

Return the root of the reversed tree.

A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.

The level of a node is the number of edges along the path between it and the root node.

 

Example 1:

Input: root = [2,3,5,8,13,21,34]
Output: [2,5,3,8,13,21,34]
Explanation: 
The tree has only one odd level.
The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.

Example 2:

Input: root = [7,13,11]
Output: [7,11,13]
Explanation: 
The nodes at level 1 are 13, 11, which are reversed and become 11, 13.

Example 3:

Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]
Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]
Explanation: 
The odd levels have non-zero values.
The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.
The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.

 

Constraints:

Java

Source file
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public TreeNode reverseOddLevels(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int currLevel = 0, nodesAtLevel;
        while (!q.isEmpty()) {
            nodesAtLevel = q.size();
            List<TreeNode> currLevelNodes = new ArrayList<>();
            while (nodesAtLevel-- > 0) {
                TreeNode node = q.poll();
                currLevelNodes.add(node);
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
            }
            if (currLevel % 2 == 1) {
                int lt = 0, rt = currLevelNodes.size() - 1;
                while (lt < rt) {
                    int temp = currLevelNodes.get(lt).val;
                    currLevelNodes.get(lt).val = currLevelNodes.get(rt).val;
                    currLevelNodes.get(rt).val = temp;
                    lt++;
                    rt--;
                }
            }
            currLevel++;
        }
        return root;
    }
}