判断B是否是A的子树 用了递归加先序遍历的非递归
#include <iostream>#include<string>#include<vector>#include<algorithm>#include<stdlib.h>#include<unordered_map>#include<set>#include<stack>#in...
·
#include <iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<stdlib.h>
#include<unordered_map>
#include<set>
#include<stack>
#include <iostream>
#include <memory>
using namespace std;
struct node {
int val;
node *left;
node *right;
node(int a) {
val = a;
left = nullptr;
right = nullptr;
}
};
bool compare2tree(node *root1, node *root2)
{
if (root1 == NULL && root2 == NULL)
return true;
else if (root1 == NULL)
return false;
else if (root2 == NULL)
return false;
else
return root1->val ==root2->val && compare2tree(root1->left, root2->left) && compare2tree(root1->right, root2->right);
}
bool Judge_Tree_is_in_ornot(node *root1, node *root2)
{
if (root1 == NULL && root2 != NULL)
return false;
if (root1 == NULL && root2 == NULL)
return true;
else
{
node *p = root1;
stack<node *>temp;
while (p || !temp.empty())
{
while (p)
{
if (p->val == root2->val)
{
if (compare2tree(p, root2))
return true;
}
temp.push(p);
p = p->left;
}
if (!temp.empty())
{
p = temp.top();
temp.pop();
p = p->right;
}
}
return false;
}
}
int main()
{
node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->right->left = new node(6);
root->right->right = new node(7);
node *root2 = new node(2);
root2->left = new node(4);
root2->right = new node(5);
cout << Judge_Tree_is_in_ornot(root, root2);
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)