劍指offer——從上往下列印二叉樹C++

baixiaofei567發表於2020-12-26

在這裡插入圖片描述

/*
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) {
        vector<int> res;
        if(root == NULL) return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* topNode = q.front();
            q.pop();
            res.push_back(topNode->val);
            if(topNode->left) q.push(topNode->left);
            if(topNode->right) q.push(topNode->right);
        }
        return res;
    }
};

相關文章