https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
按照层次遍历,先从左到右,再从右到左,依次如此遍历二叉树
仍然按照从左到右层次遍历,存储上一层的遍历方向,判断若本次应该从右到左,将本层结点遍历结果倒序即可。
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ret;
if (!root) {
return ret;
}
vector<TreeNode*> levelNodes = {root};
bool isLeftToRight = true;
while (!levelNodes.empty()) {
vector<TreeNode*> nextLevelNodes;
vector<int> levelRet;
for (TreeNode* node : levelNodes) {
levelRet.push_back(node->val);
if (node->left) {
nextLevelNodes.push_back(node->left);
}
if (node->right) {
nextLevelNodes.push_back(node->right);
}
}
if (levelRet.size()) {
if(!isLeftToRight) {
reverse(levelRet.begin(), levelRet.end());
}
ret.push_back(levelRet);
}
levelNodes = nextLevelNodes;
isLeftToRight = !isLeftToRight;
}
return ret;
}
};
【LeetCode】103. Binary Tree Zigzag Level Order Traversal
原文:https://www.cnblogs.com/AndrewGhost/p/12219924.html