/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: vector<vector<int>> printFromTopToBottom(TreeNode* root){ vector<vector<int>> res; queue<TreeNode*> q; if (!root) return res; q.push(root); q.push(nullptr); vector<int> level; while (q.size()) { auto t = q.front(); q.pop(); if (!t) { if (level.empty()) break; res.push_back(level); level.clear(); q.push(nullptr); continue; } level.push_back(t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } }
vector<vector<int>> printFromTopToBottom2(TreeNode* root){ vector<vector<int>> res; vector<int> level; queue<TreeNode*> q; if (!root) return res; q.push(root); while (q.size()) { int qs = q.size(); //必须赋值到局部变量 for (int i = 0; i < qs; ++i) { auto t = q.front(); q.pop(); level.push_back(t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } res.push_back(level); level.clear(); } } };
q.push_back(make_pair(0, root)); while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { PIT p = q.top(); q.pop(); m[p.first].push_back(p.second.val); if (p.second->left) q.push_back(make_pair(p.first - 1, p.second->left)); if (p.second->right) q.push_back(make_pair(p.first - 1, p.second->right)); } } }