45. 之字形打印二叉树

  1. 将根节点插入队列中;
  2. 创建一个新队列,用来按顺序保存下一层的所有子节点;
  3. 对于当前队列中的所有节点,按顺序依次将儿子插入新队列;
  4. 按从左到右、从右到左的顺序交替保存队列中节点的值;
  5. 重复步骤2-4,直到队列为空为止。
/**
 * 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) {
        if (!root) return {};
        vector<vector<int>> res;
        queue<TreeNode*> q;
        q.push(root);

        bool flag = false;
        while (q.size()) {
            int cnt = q.size();
            vector<int> level(cnt);
            for (int i = 0; i < cnt; i++) {
                TreeNode* t = q.front();
                q.pop();

                level[i] = t->val;
                
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            if (flag) reverse(level.begin(), level.end());
            res.push_back(level);
            flag = !flag;
        }
        
        return res;
    }
};

45. 之字形打印二叉树

上一篇:CF375D Tree and Queries(dsu)


下一篇:CrackMe34