JZ32 题解 | #从上往下打印二叉树#
从上往下打印二叉树
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 <deque> using namespace std; class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> res; if (root == nullptr) { return res; } // 二叉树的层序遍历,借助队列保存每一层节点 deque<TreeNode*> myDeque; myDeque.push_back(root); while (!myDeque.empty()) { // 获取队列中的元素长度 int sz = myDeque.size(); // 遍历队列中的每一层节点 for (int i = 0; i < sz; i++) { TreeNode* front = myDeque.front(); if (front != nullptr) { res.push_back(front->val); } myDeque.pop_front(); if (front->left != nullptr) { myDeque.push_back(front->left); } if (front->right != nullptr) { myDeque.push_back(front->right); } } } return res; } };