Sword Points Offer_Programming Questions_20

Topic description

Each node of the binary tree is printed from top to bottom, and the nodes of the same level are printed from left to right.
 
/*
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*>q;
        vector<int>vt;
        if(root == NULL)
            return vt;
        q.push(root);
        vt.push_back(root->val);
        while(!q.empty()){
            TreeNode* tmp = q.front();
            q.pop();
            if(tmp->left != NULL){
                vt.push_back(tmp->left->val);
                q.push(tmp->left);
            }
            if(tmp->right != NULL){
                vt.push_back(tmp->right->val);
                q.push(tmp->right);
            }
        }
        return vt;
    }
};

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324976342&siteId=291194637