DEV Community

SalahElhossiny
SalahElhossiny

Posted on

2

Reverse Odd Levels of Binary Tree

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

For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].
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.

class Solution {

    public void revOdd(TreeNode root1, TreeNode root2, int level){
        if((root1.left == null && root1.right == null) || (root2.left == null && root2.right == null)) return;

        if(level % 2 == 0){
            int temp = root1.left.val;
            root1.left.val = root2.right.val;
            root2.right.val = temp;
        }

        revOdd(root1.left, root2.right, level+1);
        revOdd(root1.right, root2.left, level+1);

    }

    public TreeNode reverseOddLevels(TreeNode root) {
        revOdd(root, root, 0);
        return root;
    }
}


Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay