[InterviewBit] Reverse Level Order

Reverse Level Order

  • Time :
  • Space :
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* node, vector<vector<int>>& seq, int dep) {
if(!node) return;
if(seq.size() == dep) seq.emplace_back();
seq[dep].push_back(node->val);
dfs(node->left, seq, dep + 1);
dfs(node->right, seq, dep + 1);
}
vector<int> Solution::solve(TreeNode* A) {
vector<vector<int>> seq;
dfs(A,seq,0);
vector<int> res;
for(int i = seq.size() - 1; i >= 0; i--) {
for(int j = 0; j < seq[i].size(); j++) {
res.push_back(seq[i][j]);
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/04/PS/interviewbit/reverse-level-order/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.