Description] [Problems
to binary list structure for storage, preparation of a binary tree algorithm width (the number of nodes having the largest number of nodes that layer).
[Input] form two lines, the first line is extended sequence preorder traversal of a binary tree.
[Form] the width of the output of a binary tree.
Sample input] [AB # D ## C ##
[output] Sample
2
Analysis:
1. The binary tree node
2. The input node
3. The traversing the tree to find the maximum width of
4 printouts
Binary tree node
template <typename DataType>
struct BiNode
{
DataType data;
BiNode<DataType>*lchild,*rchild;
};
template<typename DataType>
class BiTree
{
public:
BiTree()
{
root=Create();
}
int Width();//不用递归调用的函数 不用再在private里写一个同名函数了
private:
BiNode<DataType>*Create();
BiNode<DataType>*root;
};
Input node
BiNode<DataType>*BiTree<DataType>::Create()
{
BiNode<DataType>*bt;
char ch;
cin>>ch;
if(ch=='#')
bt=NULL;
else
{
bt=new BiNode<DataType>;
bt->data=ch;
bt->lchild=Create();
bt->rchild=Create();
}
return bt;
}
Using the function to find a maximum width
add desired library functions
c ++ function queues using
basic operations: header #include <queue>
Push (x) x is pressed into the end of the queue
pop () first element (team top element), pop-up queue Note that this function does not return any value
front () returns the first element (top team elements)
back () Returns the last element is pressed into (the tail element)
empty () when the queue is empty, return true
size () returns the length of the queue
int BiTree<DataType>::Width()
{
queue<BiNode<DataType>*>Q;//申请一个队列 队列的类型为结点类型的 :<BiNode<DataType>*>
int w;
if(root==NULL)//树为空 宽度为零
return 0;
else
{
Q.push(root);//根节点入队
w=1;
int maxw;//设一个整形变量 存最大值
maxw=w;
while(!Q.empty())//判断队列是否为空 空了代表遍历完成
{
for(int i=0;i<w;i++)//该结点出队 它的子结点入队
{
if(Q.front()->lchild!=NULL)
Q.push(Q.front()->lchild);
if(Q.front()->rchild!=NULL)
Q.push(Q.front()->rchild);
Q.pop();//该结点出队
}
w=Q.size();
if(maxw<w)//保证每次 maxw都会是最大的
maxw=w;
}
return maxw;
}
The main function
int main()
{
BiTree<char>t1;
cout<<t1.Width();
}
If there is a next white inappropriate place please correct me