题目:43. 把二叉树打印成多行
知识点:二叉树
题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路:
主要是使用 BFS ,通过使用队列来对节点进行保存,保证节点的先进先出,同时对每一层的入列和出列的节点进行计数,以此判断每一层的结束位置。
代码:
//解法一(自研):
vector<vector<int>> Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot == nullptr) return res;
vector<int> array;
queue<TreeNode*> s;
s.push(pRoot);
int count = 1;
while(!s.empty()){
while(count-- > 0){
TreeNode* node = s.front();
s.pop();
if(node->left != nullptr) s.push(node->left);
if(node->right != nullptr) s.push(node->right);
array.push_back(node->val);
}
res.push_back(array);
array.clear();
count = s.size();
}
return res;
}
//解法二(剑指Offer 思路同上):
void Print(BinaryTreeNode* pRoot)
{
if(pRoot == nullptr)
return;
std::queue<BinaryTreeNode*> nodes;
nodes.push(pRoot);
int nextLevel = 0;
int toBePrinted = 1;
while(!nodes.empty())
{
BinaryTreeNode* pNode = nodes.front();
printf("%d ", pNode->m_nValue);
if(pNode->m_pLeft != nullptr)
{
nodes.push(pNode->m_pLeft);
++nextLevel;
}
if(pNode->m_pRight != nullptr)
{
nodes.push(pNode->m_pRight);
++nextLevel;
}
nodes.pop();
--toBePrinted;
if(toBePrinted == 0)
{
printf("\n");
toBePrinted = nextLevel;
nextLevel = 0;
}
}
}