题解 | #从上往下打印二叉树#
从上往下打印二叉树
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) { } };*/ 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 size = q.size(); for (int i = 0; i < size; ++i) { TreeNode* tmp = q.front(); q.pop(); res.push_back(tmp->val); if (tmp->left) q.push(tmp->left); if (tmp->right) q.push(tmp->right); } } return res; } };
2023-剑指-二叉树 文章被收录于专栏
2023-剑指-二叉树