标签:display pop des hide splay i++ click example lap
Given a binary tree, return the zigzag level order traversal of its nodes‘ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ 9 20
/ 15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
1 class Solution { 2 public: 3 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 4 deque<TreeNode*>q,p; 5 vector<vector<int>>ans; 6 if (!root)return ans; 7 int i = 0; 8 q.push_back(root); 9 ans.push_back(vector<int>()); 10 ans[0].push_back(root->val); 11 while (!q.empty()) { 12 while (!q.empty()) { 13 TreeNode*now; 14 if (i % 2 == 0) { 15 now = q.front(); q.pop_front(); 16 } 17 else { 18 now = q.back(); q.pop_back(); 19 } 20 if (now->left) { 21 if (i % 2 == 0) 22 p.push_front(now->left); 23 else 24 p.push_back(now->left); 25 } 26 if (now->right) { 27 if (i % 2 == 0) 28 p.push_front(now->right); 29 else 30 p.push_back(now->right); 31 } 32 } 33 if(!p.empty()) 34 ans.push_back(vector<int>()); 35 while (!p.empty()) { 36 q.push_back(p.front()); 37 ans[i+1].push_back(p.front()->val); 38 p.pop_front(); 39 } 40 i++; 41 } 42 return ans; 43 } 44 };
19.3.5 [LeetCode 103] Binary Tree Zigzag Level Order Traversal
标签:display pop des hide splay i++ click example lap
原文地址:https://www.cnblogs.com/yalphait/p/10475158.html