← All solutions

Reverse Odd Levels Of Binary Tree

May 31, 2025 • Go •binary tree, depth first search • easy

Problem

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

Approach

  • 1. Check if level % 2 == 0, because I did it at even levels.
  • 2. Swap the nodes values in place rather than the children like in Invert Tree

Reflections

The only thing I didn't have right for the longest time was not send left of one node and right of the other until I read the second hint.

Go Solution

func reverseOddLevels(root *TreeNode) *TreeNode {
    level := 0    

    var dfs func(node, node2 *TreeNode, level int) (*TreeNode, *TreeNode)
    dfs = func(node,  node2 *TreeNode, level int) (*TreeNode, *TreeNode) {
        if node == nil {
            return nil,nil
        }

        dfs(node.Left, node2.Right, level + 1)
        dfs(node.Right,node2.Left, level + 1)

        if level % 2 == 0 {
            node.Val,node2.Val = node2.Val,node.Val
        }

        return node, node2
    }

    if root.Left == nil {
        return root
    }

    dfs(root.Left, root.Right, level)
    return root
}
LeetCode Problem Link