2415. Reverse Odd Levels of Binary Tree in JavaScript

Santosh yadav
Sep 18, 2022

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.

Solution

var reverseOddLevels = function(root) {
function reverse(t1,t2,level){
if(t1==null || t2==null) return
if(level&1){ //number&1==1=> number is odd
let tmep=0;
temp=t1.val;
t1.val=t2.val
t2.val=temp;
}
reverse(t1.left,t2.right,level+1);
reverse(t1.right,t2.left,level+1)
}
reverse(root.left,root.right,1)
return root

};

--

--

Santosh yadav

Santosh Yadav is a Lead Frontend Engineer having interest in problem solving, data structures and algorithms.