Print a binary tree from top to bottom in no line order.
- Control of boundary conditions
- Add each node into a sequence and print in sequence
Say nothing but code directly
void printFromTopBottom(TreeNode*pTreeRoot){ if (!pTreeRoot ) { return; } //queue std:deque<TreeNode*> dequeTreeNode; dequeTreeNode.push_back(pTreeRoot); while (dequeTreeNode.size()) { TreeNode*pNode = dequeTreeNode.front(); dequeTreeNode.pop_front(); printf("%d",pNode->val); if (pNode->leftNode) { dequeTreeNode.push_back(pNode->leftNode); } if (pNode->rightNode) { dequeTreeNode.push_back(pNode->rightNode); } } }
When printing the current node, add the left and right nodes of the current node to the end of the deque ue in order to print in order.
Now print the binary tree in line order
Through analysis, we think
Record the number of prints to be printed on the next line through a variable
-
Variable counts the number of nodes to print on the current line, breaking when the number is 0.Number of empty nextLines.And assign the number of nextLines to be printed.
//Print binary trees in line order
void printTree(TreeNode*pTreeRoot){ if (!pTreeRoot ) { return; } // One record is left to be printed.Number of rows in a record int toBePrint = 1; int nextLevel = 0; std::deque<TreeNode*> queue; queue.push_front(pTreeRoot); while (!queue.empty()) { TreeNode*pNode = queue.front(); queue.pop_front(); printf("%d",pNode->val); if (pNode->leftNode) { queue.push_back(pNode->leftNode); nextLevel++; } if (pNode->rightNode) { queue.push_back(pNode->rightNode); nextLevel++; } toBePrint -- ; if (toBePrint == 0) { printf("\n"); toBePrint = nextLevel; nextLevel = 0; } } }