// 面试题32(二):分行从上到下打印二叉树 // 题目:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层 // 打印到一行。 #include <cstdio> #include "BinaryTree.h" #include <queue> void Print(BinaryTreeNode* pRoot) { if (pRoot == nullptr) return; std::queue<BinaryTreeNode*> dequeTreeNode; dequeTreeNode.push(pRoot); int nextLevel = 0; //下一层中需要打印的次数 int toBePrinted = 1; //当前层需要打印的次数 while (!dequeTreeNode.empty()) { BinaryTreeNode* pNode = dequeTreeNode.front(); dequeTreeNode.pop(); printf("%d ", pNode->m_nValue); if (pNode->m_pLeft) { dequeTreeNode.push(pNode->m_pLeft); ++nextLevel; } if (pNode->m_pRight) { dequeTreeNode.push(pNode->m_pRight); ++nextLevel; } --toBePrinted; //打印次数-1 if (toBePrinted == 0) //当前层打印完成, 重置数据 { toBePrinted = nextLevel; nextLevel = 0; printf(" "); } } }
分析:额外设置标志位来控制回车。此时不需要deque(两端都可以进入的栈)。
牛客网返回一个二维容器,详情见代码。
/* 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) { std::queue<TreeNode*> queueTreeNode; int nextLevel = 0; int toBePrint = 1; std::vector<std::vector<int> > printTreeNode; std::vector<int> printTemp; if (pRoot == nullptr) return printTreeNode; queueTreeNode.push(pRoot); while (!queueTreeNode.empty()) { TreeNode* pNode = queueTreeNode.front(); queueTreeNode.pop(); printTemp.push_back(pNode->val); if (pNode->left) { queueTreeNode.push(pNode->left); ++nextLevel; } if (pNode->right) { queueTreeNode.push(pNode->right); ++nextLevel; } --toBePrint; if (toBePrint == 0) { toBePrint = nextLevel; nextLevel = 0; printTreeNode.push_back(printTemp); printTemp.clear(); } } return printTreeNode; } };