题解 | #从上往下打印二叉树#
从上往下打印二叉树
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 <queue> #include <vector> class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> v; if (!root) return v; // 题目意思就是层序遍历 queue<TreeNode*> q; q.push(root); while (!q.empty()) { int num = q.size(); for(int i = 0; i < num; ++i) { TreeNode* tmp = q.front(); q.pop(); if(tmp) v.push_back(tmp->val); if (tmp->left) { q.push(tmp->left); } if(tmp->right) { q.push(tmp->right); } } } return v; } };
挤挤刷刷! 文章被收录于专栏
记录coding过程