[Problem description]
Taking the binary linked list as the storage structure, write an algorithm to find the layer number of the node with value x in the binary tree.
[Input form] Two lines, the first line is the preorder traversal sequence of the extended binary tree, and the second line is the node x to be queried
[Output form] the node number where the value is x. The layer where the root node is located is recorded as the first layer.
[Sample input] AB # D ## C ##
D
[Sample output]
3
Analysis:
1. Construct a binary tree node
2. Enter the value of the node
3. Traverse the number of record layers
4. Determine the output result
Construct a binary tree node
template <typename DataType>
struct BiNode
{
DataType data;
BiNode<DataType>*lchild,*rchild;
};
template<typename DataType>
class BiTree
{
public:
BiTree()
{
root=Create();
}
int LevelNum(DataType x)
{
return LevelNum(root,1,x);//这里level初始化为1
}
private:
BiNode<DataType>*Create();
int LevelNum(BiNode<DataType>*bt,int level,DataType x);
BiNode<DataType>*root;
};
Enter node value
template<typename DataType>
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;
}
Traverse the record layer
int BiTree<DataType>::LevelNum(BiNode<DataType>*bt,int level,DataType x)
{
if(bt==NULL)//两种情况 树为空 或者 未找到 x
return 0;
else
{
if(bt->data==x)//找到x 返回层数
return level;
else
{
int l1=0;
l1=LevelNum(bt->lchild,level+1,x);//利用递归 继续寻找左子树 注意层数要增加
if(l1!=0)
return l1;
else
{
int l2=0;
l2=LevelNum(bt->rchild,level+1,x);//利用递归 继续寻找右子树 注意层数要增加
if(l2!=0)
return l2;
else
return 0;//最后没找到 返回0
}
}
}
}
Main function
int main()
{
BiTree<char>t1;
char x;
cin>>x;
cout<<t1.LevelNum(x);
}
Below is a little white. If there is an inappropriate place, please correct me.