试题链接:https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&&tqId=11175&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
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;
queue<TreeNode*> q;
if(root == NULL){
return ret;
}
q.push(root);
while(!q.empty()){
if(q.front()->left != NULL){
q.push(q.front()->left);
}
if(q.front()->right != NULL){
q.push(q.front()->right);
}
ret.push_back(q.front()->val);
q.pop();
}
return ret;
}
};
一个简单的层序遍历二叉树,加了一个队列实现。