标签:void cin color double b树 结构 思路 cout stream
输入两颗二叉树A,B,判断B是不是A的子结构。
#include <iostream> using namespace std; struct tree { double data; struct tree *left,*right; tree(int d=0):data(d) { left=right=nullptr; } }; class Solution { public: void create(tree *&root); void pre_order(tree *root); bool has_tree(tree *r1,tree *r2); bool has_tree_core(tree *r1,tree *r2); bool equal(double a,double b); tree *root; }; void Solution::create(tree *&root) { double x; cin>>x; if(x==0) root=nullptr; else { root=new tree(); root->data=x; create(root->left); create(root->right); } } bool Solution::has_tree(tree *r1,tree *r2) { bool res=false; if(r1&&r2) { if(equal(r1->data,r2->data)) res=has_tree_core(r1,r2); if(!res) res=has_tree(r1->left,r2); if(!res) res=has_tree(r1->right,r2); } return res; } bool Solution::has_tree_core(tree *r1,tree *r2) { //循环结束条件是各自到达了自己的叶子结点 if(!r2) return true;//r2到达了叶子结点,返回true if(!r1) return false;//r1到达了叶子结点,r2还没到达,返回false if(!equal(r1->data,r2->data)) return false; return has_tree_core(r1->left,r2->left)&&has_tree_core(r1->right,r2->right); } bool Solution::equal(double a,double b) { if((a-b>-0.0000001)&&(a-b<0.0000001)) return true; else return false; } void Solution::pre_order(tree *root) { if(root) { cout<<root->data<<endl; pre_order(root->left); pre_order(root->right); } } int main() { Solution s,S; s.create(s.root); S.create(S.root); //s.pre_order(s.root); cout<<s.has_tree(s.root,S.root)<<endl; return 0; }
标签:void cin color double b树 结构 思路 cout stream
原文地址:https://www.cnblogs.com/tianzeng/p/10180232.html