牛客网题目
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&tPage=3&rp=3&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<vector<int> > Print(TreeNode* pRoot) { vector<vector<int> > ans; if(pRoot == nullptr) return ans; queue<TreeNode*> q; q.push(pRoot); while(!q.empty()){ vector<int> temp; for(int i = 0, n = q.size(); i < n; i++){ TreeNode* curNode = q.front(); q.pop(); temp.push_back(curNode->val); if(curNode->left) q.push(curNode->left); if(curNode->right) q.push(curNode->right); } ans.push_back(temp); } return ans; } };