Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Java/ReverseOddLevelsOfBinaryTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.ArrayList;
import java.util.List;

public class ReverseOddLevelsOfBinaryTree {
/**
Store all the level's data in a list by simply any traversal(pre-order here)
Then again traverse the tree and when found the odd level,
change the root data with the last element of the level-list and remove the last item
*/
public TreeNode reverseOddLevels(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
tra(list, root, 0);
modify(list, root, 0);
return root;
}
private void modify(List<List<Integer>> res, TreeNode root, int level){
if(root == null) return;

// Odd level
if((level%2) != 0){

// Modify root data with last item of list, and then remove the last item
List<Integer> lvlArr = res.get(level);
root.val = lvlArr.get(lvlArr.size()-1);
lvlArr.remove(lvlArr.size()-1);
}

modify(res,root.left,level+1);
modify(res,root.right,level+1);
}

// generate list with level-order items
private void tra(List<List<Integer>> res, TreeNode root, int level){
if(root == null) return;

if(level >= res.size())
res.add(new ArrayList<>());

res.get(level).add(root.val);
tra(res,root.left,level+1);
tra(res,root.right,level+1);
}

static class TreeNode{
int val;
TreeNode left;
TreeNode right;

public TreeNode() {}
TreeNode(int val) { this.val = val; }
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | [Javascript](./JavaScript/98.Validate-Binary-Search-Tree.js) | _O(log(n))_ | _O(log(n))_ | Medium | Binary Tree |
| 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [Java](./Java/Redundant-Connection/redundant-connection.java) | _O(N)_ | _O(N)_ | Medium | Tree, Union Find |
| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) |[C++](./C++/Binary-Tree-Level-Order-Traversal.cpp)| _O(n)_ | _O(n)_ | Medium | Binary Tree, map | |
| 2415 | [Reverse Odd Levels of Binary Tree](https://leetcode.com/problems/reverse-odd-levels-of-binary-tree) | [Java](./Java/ReverseOddLevelsOfBinaryTree.java) | _O(n)_ | _O(n)_ | Medium | Binary Tree

<br/>
<div align="right">
Expand Down