牛客-二叉樹層序遍歷

牛客-二叉樹層序遍歷

#include <stdio.h>
#include <queue>
#include <stack>
#include <math.h>
#include <map>
#include <string.h>
#include <string>
#include <set>
using namespace std;


struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};


class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        queue<TreeNode*> q1;
        vector<int> res;
        if (root==NULL) return res;
        q1.push(root);
//        res.push_back(root->val);
        while (!q1.empty()) {
            TreeNode* temp = q1.front();
            res.push_back(temp->val);
            q1.pop();
            if (temp->left != NULL) {
                q1.push(temp->left);
                
            }
            if (temp->right != NULL) {
                q1.push(temp->right);
            }
        }
        return res;

    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章