采用广度优先遍历,一个变量记录层数,一个变量记录方向.
void traverse(TreeNode *root, vector<vector<int>> result, int level, bool left_to_right) { if (!root)return; //如果进入下一层了,则result同样也加一层 if (level > result.size())result.push_back(vector<int>()); //如果此时为从左向右,则直接压入即可 if (left_to_right) result[level - 1].push_back(root->val); //如果此时从右向左,则从头插入 else result[level - 1].insert(result[level - 1].begin(), root->val); traverse(root->left, result, level + 1, !left_to_right); traverse(root->right, result, level + 1, !left_to_right); } vector<vector<int>> zigzagLevelOrder(TreeNode *root) { //广度优先遍历 vector<vector<int>> result; traverse(root, result, 1, true); return result; }