[InterviewBit] ZigZag Level Order Traversal BT

ZigZag Level Order Traversal BT

  • 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void helper(vector<vector<int>>& res, int level, TreeNode* node) {
if(!node) return;
if(res.size() == level) res.emplace_back();
res[level].push_back(node->val);
helper(res,level + 1, node->left);
helper(res,level + 1, node->right);
}
vector<vector<int>> Solution::zigzagLevelOrder(TreeNode* A) {
vector<vector<int>> res;
helper(res, 0, A);
for(int i = 1; i < res.size(); i += 2) reverse(begin(res[i]), end(res[i]));
return res;
}

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