【剑指Offer-举例让抽象问题具体化】面试题32:从上到下打印二叉树

题目描述1

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路

二叉树的层次遍历(bfs),使用队列求解,代码如下:

/*
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> ans;
        if(root==nullptr)
            return ans;
        
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* cur = q.front();
            ans.push_back(cur->val);
            q.pop();
            if(cur->left!=nullptr)
                q.push(cur->left);
            if(cur->right!=nullptr)
                q.push(cur->right);
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/flix/p/12466432.html