剑指 Offer刷题记录| 32 - I. 从上到下打印二叉树,32 - II. 从上到下打印二叉树 II,32 - III. 从上到下打印二叉树 III

剑指 Offer 32 - I. 从上到下打印二叉树

题目链接:剑指 Offer 32 - I. 从上到下打印二叉树

class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        vector<int> result;
        queue<TreeNode *> s;
        s.push(root);
        while(!s.empty()){
            TreeNode * temp = s.front();
            if(temp == nullptr){
                s.pop();
                continue;
            }
            result.push_back(temp->val);
            s.pop();
            s.push(temp->left);
            s.push(temp->right);
        }
        return result;
    }
};

剑指 Offer 32 - II. 从上到下打印二叉树 II

题目链接:剑指 Offer 32 - II. 从上到下打印二叉树 II

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        if(root == NULL)return result;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty()){
            int qLength = q.size(); //记录需要进行循环的次数
            vector<int> v;
            for(int i = 0; i < qLength; i++){ //通过嵌套for循环进行对一层数据的写入
                TreeNode * temp = q.front();
                v.push_back(temp->val);
                q.pop();
                if(temp->left)q.push(temp->left);
                if(temp->right)q.push(temp->right);
            }
            result.push_back(v);
        }
        return result;
    }
};

剑指 Offer 32 - III. 从上到下打印二叉树 III

题目链接:剑指 Offer 32 - III. 从上到下打印二叉树 III

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        if(root == NULL)return result;
        queue<TreeNode *> q;
        bool flag = true; //设置标记,用来判断是当前行是反转还是正序
        q.push(root);
        while(!q.empty()){
            int qLength = q.size();
            vector<int> v;
            for(int i = 0; i < qLength; i++){
                TreeNode * temp = q.front();
                if(flag){								//正常顺序
                    v.push_back(temp->val);
                }else{									//需要在容器头部插入实现倒序
                    v.insert(v.begin(), temp->val);
                }
                q.pop();
                if(temp->left)q.push(temp->left);
                if(temp->right)q.push(temp->right);
            }
            flag = !flag;			//经历过一次正序后进行倒序
            result.push_back(v);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值