NC267. 从上往下打印二叉树
描述
示例1
输入:
{8,6,10,#,#,2,1}
输出:
[8,6,10,2,1]
示例2
输入:
{5,4,#,3,#,2,#,1}
输出:
[5,4,3,2,1]
C++ 解法, 执行用时: 2ms, 内存消耗: 524KB, 提交时间: 2022-02-09
/* 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> ret; if (!root) { return ret; } queue<TreeNode*> q; q.push(root); while(!q.empty()) { int size = q.size(); for (int i=0; i<size; i++) { TreeNode *p = q.front(); q.pop(); ret.push_back(p->val); if (p->left) { q.push(p->left); } if (p->right) { q.push(p->right); } } } return ret; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 544KB, 提交时间: 2022-02-10
/* 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> ret; if(root==nullptr)return ret; queue<TreeNode*> qq; qq.push(root); while(!qq.empty()) { TreeNode*rt=qq.front(); qq.pop(); ret.push_back(rt->val); if(rt->left!=nullptr) qq.push(rt->left); if(rt->right!=nullptr) qq.push(rt->right); } return ret; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 556KB, 提交时间: 2022-02-10
/* 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) { queue<TreeNode*> q; if(root != NULL) { q.push(root); } vector<int> ans; while(!q.empty()){ int size = q.size(); for(int i = 0; i < size; ++i){ ans.push_back(q.front()->val); if(q.front()->left) { q.push(q.front()->left); } if(q.front()->right) { q.push(q.front()->right); } q.pop(); } } return ans; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 556KB, 提交时间: 2021-11-23
/* 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) return res; queue<TreeNode*> q; q.push(root); while(!q.empty()) { auto t=q.front(); if(t->left) q.push(t->left); if(t->right) q.push(t->right); q.pop(); res.push_back(t->val); } return res; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 604KB, 提交时间: 2022-03-12
/* 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 == NULL) return res; queue<TreeNode*> que; que.push(root); TreeNode* node = NULL; while (!que.empty()) { node = que.front(); res.push_back(node->val); que.pop(); if (node->left != NULL) que.push(node->left); if (node->right != NULL) que.push(node->right); } return res; } };