解法:广搜遍历
/*
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;
}
};

京公网安备 11010502036488号