【LeetCode】103. Binary Tree Zigzag Level Order Traversal

题目地址

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

题目大意

按照层次遍历,先从左到右,再从右到左,依次如此遍历二叉树

解题思路

仍然按照从左到右层次遍历,存储上一层的遍历方向,判断若本次应该从右到左,将本层结点遍历结果倒序即可。

C++代码

class Solution {
public:
    vector> zigzagLevelOrder(TreeNode* root) {
        vector> ret;
        if (!root) {
            return ret;
        }
        vector levelNodes = {root};
        bool isLeftToRight = true;
        while (!levelNodes.empty()) {
            vector nextLevelNodes;
            vector 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)