首页 > 其他 > 详细

45. 之字形打印二叉树

时间:2021-07-23 23:38:01      阅读:23      评论:0      收藏:0      [点我收藏+]
  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. 之字形打印二叉树

原文:https://www.cnblogs.com/fxh0707/p/15053843.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!