/** * 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 { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { queue<TreeNode*> q; q.push(root); vector<vector<int>> v; if(root==NULL) return v; bool p=true; while(!q.empty()) { vector<int> v2; int p2=q.size(); while(p2--) { TreeNode* temp=q.front(); q.pop(); v2.push_back(temp->val); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } if(!p) { reverse(v2.begin(), v2.end()); p=true; } else p=false; v.push_back(v2); } return v; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter