Taking the binary linked list as the storage structure, write an algorithm to judge whether there is a 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] If the node x exists, output "YES"; otherwise output "NO".
[Sample input] AB # D ## C ##
D
[Sample output]
YES
analysis:
1. Construct a binary tree node
2. Enter the node value
3. Traverse
4. Judge the output result
Construct a binary tree node
template <typename DataType>
struct BiNode
{
DataType data;
BiNode<DataType>*rchild,*lchild;
}
class BiTree
{
public:
BiTree()
{
root=Create;
}
bool ExistX(DataType x)
return ExistX(root,x);
private:
BiNode<DataType>*root;
BiNode<DataType>*Create();
bool ExistX(BiNode<DataType>*bt,DataType x);
}
Use function to
input node value
template <typename DataType>
BiNode<DataType>*BiTree<DataType>::Create()
{
BiNode<DataType>*bt;
char ch;
cin>>ch;
if(ch==#)
{
return;
}
else
{
bt=new BiNode<DataType>;
bt->data=ch;
bt->rchild=Create();
bt->lchild=Create();
}
return bt;
}
Traversal detection function
template <typename DataType>
bool BiTree<DataType>::ExistX(BiNode<DataType>*bt,DataType x)
{
if(bt==NULL)//如果为空 未查到 false
return false;
else
{
if(bt->data==x)//查找的 true
{
return true;
}
else
{
if(ExistX(bt->lchild,x))
return true;//如果在左孩子找到return true
else
{
if(ExistX(bt->rchild,x))//在右孩子找到 reture true
return true;
else
return false;//都没找到 return false
}
}
}
}
Main function
int main()
{
BiTree<char>t1;
char x;
cin>>x;
if(t1.ExistX(x))
cout<<"YES";
else
cout<<"NO";
}
Below is a little white. If there is an inappropriate place, please correct me.