题解 | #从上往下打印二叉树#
从上往下打印二叉树
http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
层序遍历,队列
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
queue<TreeNode*> s;
vector<int> ans;
if(!root) return ans;
s.push(root);
while(!s.empty()){
//int size=s.size();
TreeNode* tmp;
tmp=s.front();
s.pop();
ans.push_back(tmp->val);
if(tmp->left) s.push(tmp->left);
if(tmp->right) s.push(tmp->right);
}
return ans;
}
};
查看9道真题和解析
SHEIN希音公司福利 278人发布