Sword refers to offer acwing 45 zigzag printing binary tree

Topic

Insert picture description here

answer

As in question 44, add a nullptr at the end of each layer to achieve layering, and then add a counter. When cnt is odd, put it directly into res, when cnt is even, flip cur, and put it into res

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<vector<int>> printFromTopToBottom(TreeNode *root) {
    
    
        vector<vector<int>> res;
        if (!root) return res;
        vector<int> cur;
        queue<TreeNode *> q;
        q.push(root);
        q.push(nullptr);
        int cnt = 1;
        while (q.size()) {
    
    
            auto t = q.front();
            q.pop();
            if (t) {
    
    
                cur.push_back(t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            } else {
    
    
                if (cnt & 1) res.push_back(cur);
                else {
    
    
                    reverse(cur.begin(), cur.end());
                    res.push_back(cur);
                }
                cnt++;
                cur.clear();
                if (q.size()) q.push(nullptr);
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115150144