[LeetCode] Reverse Odd Levels of Binary Tree

2415. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<int, vector<TreeNode*>> mp;
void dfs(TreeNode* node, int level) {
if(!node) return;
mp[level].push_back(node);
dfs(node->left,level+1);
dfs(node->right,level+1);
}
public:
TreeNode* reverseOddLevels(TreeNode* root) {
dfs(root,0);
int l = 1;
while(mp.count(l)) {
vector<TreeNode*>& vec = mp[l];
int lo = 0, hi = vec.size() - 1;
while(lo < hi) {
swap(vec[lo]->val,vec[hi]->val);
lo++,hi--;
}
l += 2;
}
return root;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/18/PS/LeetCode/reverse-odd-levels-of-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.