二叉树顺序遍历。采用队列,自己想不出来,参考了讲解才模仿出来,思路神奇!
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> s;
if (root == NULL)
{
return s;
}
queue <TreeNode*> q;
q.push(root);
while (!q.empty()) {
s.push_back(q.front()->val);
if (q.front()->left != NULL) {
q.push(q.front()->left);
}
if (q.front()->right != NULL) {
q.push(q.front()->right);
}
q.pop();
}
return s;
}
};