指定的节点用节点存储的数据来代表,采用递归的方法先判断当前节点是否是目标节点,若不是则依次查找左子树和右子树:
#include<iostream>
#include<stack>
using namespace std;
typedef struct tr
{
int data;
struct tr *left,*right;
}tre,* tree;
stack<tree>st;
tree creat(tree root,int val)
{
tree newroot;
if(NULL==root)
{
newroot=new tre;
newroot->data=val;
newroot->left=newroot->right=NULL;
return newroot;
}
if(val<=root->data)
root->left=creat(root->left,val);
else
root->right=creat(root->right,val);
return root;
}
void level(tree root,int val,int &ans,int lev)
{//lev为中间变量,初始值为1,记录层数
if(NULL==root)
ans=-1;
else if(root->data==val)
ans=lev;
else
{
level(root->left,val,ans,lev+1);//在左子树中查找
if(ans==-1)
level(root->right,val,ans,lev+1);//在右子树中查找
}
}
/*void lbr(tree root)
{
while(NULL!=root || !st.empty())
{
if(NULL!=root)
{
st.push(root);
root=root->left;
}
else
{
root=st.top();
st.pop();
printf("%d ",root->data);
root=root->right;
}
}
}
void blr(tree root)
{
while(NULL!=root || !st.empty())
{
if(NULL!=root)
{
printf("%d ",root->data);
st.push(root);
root=root->left;
}
else
{
root=st.top();
st.pop();
root=root->right;
}
}
}*/
int main()
{
int n;
int res;
tree tmp;
tmp=NULL;
while(scanf("%d",&n),n+1)
tmp=creat(tmp,n);
lbr(tmp);
printf("/n");
blr(tmp);
printf("/n");
while(scanf("%d",&n)!=EOF)
{
res=-1;
level(tmp,n,res,1);
printf("%d/n",res);
}
return false;
}