任何人都可以解释为什么我在这里得到两次输出?为什么在这个树程序中我得到了两次输出?
# include<iostream>
# include<conio.h>
# include <stdio.h>
using namespace std;
struct tree
{
int data;
struct tree * left;
struct tree * right;
};
struct tree * insert(struct tree * root,int value)
{
if (root==NULL)
{
struct tree * node= (struct tree *)malloc(sizeof(struct tree));
node->data=value;
node->right=NULL;
node->left=NULL;
return node;
}
else if(root->data > value)
root->left=insert(root->left,value);
else
root->right=insert(root->right,value);
}
int same_tree(struct tree * root1, struct tree* root2)
{
if((root1==NULL && root2!=NULL) || (root1!=NULL && root2==NULL))
{
cout << " tree are not equal \n";
return -1;
}
if(root1 && root2)
{
same_tree(root1->left,root2->left);
if(root1->data!=root2->data)
{
cout << "tree not equal \n";
return -1;
}
same_tree(root1->right,root2->right);
}
}
int main()
{
struct tree * root=NULL;
root= insert(root,8);
insert(root,6);
insert(root,7);
insert(root,5);
insert(root,1);
insert(root,20);
insert(root,15);
struct tree * root2=NULL;
root2= insert(root2,8);
insert(root2,6);
insert(root2,7);
insert(root2,5);
insert(root2,1);
insert(root2,20);
insert(root2,18);
int j= same_tree(root,root2);
if(j==-1)
cout << " tree not eqqual \n";
else
cout << "tree are equal\n";
getch();
return 0;
}
编写该程序是为了比较两棵树是否相同(在它们包含的同一层次结构和数据中)。我在这里比较的两棵树是从main(root和root2)传入的。 如果有相同的树,我得到一次“树相等”的O/O。但如果树不相等,我得到一个o/p“tre不相等”,并在下一行中作为“树相等”。我无法解释为什么?我编写了整个程序,以便任何人都可以复制粘贴并在系统上运行它。我想问题在于same_tree的递归调用的地方,但位置和原因是什么我没有得到
这是为什么标签的Java? – 2012-02-12 18:42:49
这是什么*语言* FrankenC++? – 2012-02-12 18:44:38
@Luchian对不起mea culpa ... untagged它 – Invictus 2012-02-12 18:45:10