简介

常规思路BFS
但是有一些点比较巧妙

code

/**
 * 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) {
        // 层次遍历
        vector<vector<int> > ans;
        if(!root){
            return ans;
        }
        queue<TreeNode*> nodeQueue;
        nodeQueue.push(root);
        bool isOrderLeft = true;
        while(!nodeQueue.empty()){
            deque<int> levelList;
            int size = nodeQueue.size();
            for(int i=0; i<size; ++i){
                auto node = nodeQueue.front();
                nodeQueue.pop();
                if(isOrderLeft){
                    levelList.push_back(node->val);
                }else{
                    levelList.push_front(node->val);
                }
                if(node->left){
                    nodeQueue.push(node->left);
                }
                if(node->right){
                    nodeQueue.push(node->right);
                }
            }
            ans.emplace_back(vector<int>{levelList.begin(), levelList.end()});
            isOrderLeft =! isOrderLeft;
        }
        return ans;
    }
};

首先,使用了deque, 双端队列, 根据当前的情况使用push_back, 还是 push_front.
其次,使用了vector零时构造函数搭配emplace_back减少,构造函数的时候, vector{levelList.begin(), levelList.end()}; 进行整段数据的迁移.

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<List<Integer>>();
        if (root == null) {
            return ans;
        }

        Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
        nodeQueue.offer(root);
        boolean isOrderLeft = true;

        while (!nodeQueue.isEmpty()) {
            Deque<Integer> levelList = new LinkedList<Integer>();
            int size = nodeQueue.size();
            for (int i = 0; i < size; ++i) {
                TreeNode curNode = nodeQueue.poll();
                if (isOrderLeft) {
                    levelList.offerLast(curNode.val);
                } else {
                    levelList.offerFirst(curNode.val);
                }
                if (curNode.left != null) {
                    nodeQueue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    nodeQueue.offer(curNode.right);
                }
            }
            ans.add(new LinkedList<Integer>(levelList));
            isOrderLeft = !isOrderLeft;
        }
        return ans;
    }
}
posted on 2021-05-16 17:47  HDU李少帅  阅读(50)  评论(0编辑  收藏  举报