力扣---二叉树的锯齿形层序遍历

时间:2024-05-05 07:11:36

给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]

思路:

层序遍历 + 双端队列(奇偶层逻辑分离)

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        deque<TreeNode*> due;
        vector<vector<int>> res;
        if (root != nullptr) due.push_back(root);

        while(!due.empty()){
            //打印奇数层
            vector<int> tmp;
            for(int i = due.size();i>0;--i){
                root = due.front();
                due.pop_front();
                tmp.push_back(root->val);
                if (root->left != nullptr) due.push_back(root->left);
                if (root->right != nullptr) due.push_back(root->right);
            }
            res.push_back(tmp);
            if(due.empty()) break;   //若为空,提前跳出
            //打印偶数层
            tmp.clear();
            for(int i = due.size();i>0;--i){
                root = due.back();
                due.pop_back();
                tmp.push_back(root->val);
                if (root->right != nullptr) due.push_front(root->right);
                if (root->left != nullptr) due.push_front(root->left);
            }
            res.push_back(tmp);
        }

        return res;
    }
};