---
# System prepended metadata

title: 2415. Reverse Odd Levels of Binary Tree
tags: [Leetcode, BFS, Tree, DFS, Medium]

---

# 2415. Reverse Odd Levels of Binary Tree
###### tags: `Leetcode` `Medium` `Tree` `DFS` `BFS`
Link: https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/description/
## Code
### DFS
```java=
class Solution {
    public TreeNode reverseOddLevels(TreeNode root) {
        traverse(root.left, root.right, 1);
        return root;
    }
    public void traverse(TreeNode node1, TreeNode node2, int level){
        if(node1==null || node2==null) return;
        if(level%2==1){
            int temp = node1.val;
            node1.val = node2.val;
            node2.val = temp;
        }
        traverse(node1.left, node2.right, level+1);
        traverse(node1.right, node2.left, level+1);
    }
}       
```
### BFS
```java=
class Solution {
    public TreeNode reverseOddLevels(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int d = 0;
        while(!q.isEmpty()){
            int size = q.size();
            for(int i=0; i<size; i++){
                TreeNode curr = q.poll();
                if(curr.left!=null) q.add(curr.left);
                if(curr.right!=null) q.add(curr.right);
            }
            d++;
            if(d%2==1 && !q.isEmpty()){
                int[] nums = new int[q.size()];
                int idx = 0;
                for(TreeNode n:q){
                    nums[idx++] = n.val;
                }
                int j = q.size()-1;
                for(TreeNode n:q){
                    n.val = nums[j--];
                }
            }
        }
        return root;
    }
}
```