59把二叉树打印成多行
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:二叉树的层次遍历。
/* 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> > res; if(pRoot == nullptr){ return res; } queue<TreeNode*> q; q.push(pRoot); while(!q.empty()){ int sz = q.size(); vector<int> tmp; for(int i = 0;i < sz;++i){ TreeNode* tmpNode = q.front(); q.pop(); tmp.push_back(tmpNode->val); if(tmpNode->left){ q.push(tmpNode->left); } if(tmpNode->right){ q.push(tmpNode->right); } } res.push_back(tmp); } return res; } };