其实就是层序遍历,我们用dfs来实现
1.先扩展根节点
2.再依次扩展左右儿子,也就是左右扩展下一层
3.再依次扩展下一层
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* 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.size())
{
auto t=q.front();
q.pop();
res.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
return res;
}
};