基本数据结构操作,二叉树的层次遍历。
代码:
1 vector<vector<int> > zigzagLevelOrder(TreeNode *root) { 2 vector<vector<int> > res; 3 vector<TreeNode *> layer; 4 bool l2r = true; 5 6 layer.push_back(root); 7 while (!layer.empty()) { 8 vector<TreeNode *> nextLayer; 9 vector<int> path; 10 for (auto node : layer) { 11 if (!node) 12 continue; 13 path.push_back(node->val); 14 nextLayer.push_back(node->left); 15 nextLayer.push_back(node->right); 16 } 17 if (!l2r) { 18 for (int i = 0; (i << 1) < path.size(); i++) 19 swap(path[i], path[path.size() - i - 1]); 20 } 21 if (!path.empty()) 22 res.push_back(path); 23 layer = nextLayer; 24 l2r = !l2r; 25 } 26 27 return res; 28 }