#include<iostream>
#include<stack>
using namespace std;
struct BinaryTreeNode
{
int m_dbValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
//创建树节点
BinaryTreeNode* CreateBinaryTreeNode(int dbValue)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_dbValue = dbValue;
pNode->m_pLeft = nullptr;
pNode->m_pRight = nullptr;
return pNode;
}
//连接结点
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if (pParent != nullptr)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
}
//释放内存
void DestroyTree(BinaryTreeNode* pRoot)
{
if (pRoot != nullptr)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight;
delete pRoot;
pRoot = nullptr;
DestroyTree(pLeft);
DestroyTree(pRight);
}
}
//分行从上到下"之"字形打印二叉树
void Print(BinaryTreeNode* pRoot)
{
if (pRoot == nullptr)
return;
//创建两个栈,一个保存当前的打印元素,一个保存下一行打印的元素
std::stack<BinaryTreeNode*> stackTreeNode[2];
int current = 0;
int next = 1;
stackTreeNode[current].push(pRoot);
while (!stackTreeNode[current].empty() || !stackTreeNode[next].empty())
{
BinaryTreeNode* pNode = stackTreeNode[current].top();
stackTreeNode[current].pop();
printf("%d ",pNode->m_dbValue);
//当奇数行时,先压入左子树到下一个栈,再压入右子树,偶数行则相反
if (current == 0)
{
if (pNode->m_pLeft != nullptr)
stackTreeNode[next].push(pNode->m_pLeft);
if (pNode->m_pRight != nullptr)
stackTreeNode[next].push(pNode->m_pRight);
}
else
{
if (pNode->m_pRight != nullptr)
stackTreeNode[next].push(pNode->m_pRight);
if (pNode->m_pLeft != nullptr)
stackTreeNode[next].push(pNode->m_pLeft);
}
//当当前行打印完,打印换行符,同时将当前栈换成下一个栈继续打印
if (stackTreeNode[current].empty())
{
printf("\n");
current = 1 - current;
next = 1 - next;
}
}
}
int main()
{
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode14 = CreateBinaryTreeNode(14);
BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode12 = CreateBinaryTreeNode(12);
BinaryTreeNode* pNode16 = CreateBinaryTreeNode(16);
ConnectTreeNodes(pNode10, pNode6, pNode14);
ConnectTreeNodes(pNode6, pNode4, pNode8);
ConnectTreeNodes(pNode14, pNode12, pNode16);
Print(pNode10);
DestroyTree(pNode10);
return 0;
}
之子形打印二叉树
猜你喜欢
转载自blog.csdn.net/weixin_39916039/article/details/82597289
今日推荐
周排行