题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ #include <vector> class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> res; if (root == nullptr) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int cnt = q.size(); while (cnt > 0) { TreeNode *temp = q.front(); q.pop(); res.push_back(temp->val); if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); cnt--; } } return res; } };