从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:层次遍历,使用queue,压入根节点,然后看左右子树,只要不为空就继续压进去。
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution {public: vector PrintFromTopToBottom(TreeNode* root) { queueq; vector result; if(root == nullptr){ return result; } q.push(root); while(!q.empty()){ TreeNode* tmp = q.front(); q.pop(); result.push_back(tmp -> val); if(tmp -> left != nullptr){ q.push(tmp -> left); } if(tmp -> right != nullptr){ q.push(tmp -> right); } } return result; }};