#include <iostream> #include<queue> using namespace std; struct treeNode { int value; treeNode* left; treeNode* right; treeNode* parent; };//节点结构 void insert(treeNode **root,int value) { treeNode* toBe=new treeNode; toBe->value=value; toBe->parent=NULL; toBe->left=toBe->right=NULL; if(*root==NULL) { *root=toBe; return ; } treeNode* temp=*root,*p1=NULL; while(temp) { p1=temp; if(temp->value>value) temp=temp->left; else temp=temp->right; } if(p1->value>value) p1->left=toBe; else p1->right=toBe; toBe->parent=p1; }
//此处是相关的代码 <strong>bool isSameTree(treeNode* root1,treeNode*root2) { if(root2==NULL&&root1==NULL)//两个都等于NULL return true; if(root1==NULL||root2==NULL)//只有一个等于NULL return false; if(root1->value==root2->value) return isSameTree(root1->left,root2->left)&&isSameTree(root1->right,root2->right); else return false; } bool isSubTree(treeNode* root1,treeNode *root2) { bool isSub=false; if(root1!=NULL) { if(root1->value==root2->value) { isSub=isSameTree(root1,root2); } if(!isSub) isSub=isSubTree(root1->left,root2); if(!isSub) isSub=isSubTree(root1->right,root2); } return isSub; } </strong> int getHeight(treeNode* root) { if(root==NULL) return 0; return getHeight(root->left)>getHeight(root->right)? (getHeight(root->left)+1):(getHeight(root->right)+1); } void printByLevel(treeNode *root,int level) { if(root==NULL||level<0) return ; else if (level==0) { cout<<root->value<<" "; return ; } else { printByLevel(root->left,level-1); printByLevel(root->right,level-1); } } int main() { treeNode* root=NULL,*root2=NULL; insert(&root,20); insert(&root,10); insert(&root,30); insert(&root,15); insert(&root,25); insert(&root,35); insert(&root,5); insert(&root2,10); insert(&root2,5); insert(&root2,100); int high=getHeight(root); for(int i=0;i!=high;i++) { printByLevel(root,i); cout<<endl; cout<<"---------"<<endl; } int high2=getHeight(root2); for(int i=0;i!=high2;i++) { printByLevel(root2,i); cout<<endl; cout<<"---------"<<endl; } cout<<isSubTree(root,root2); }
时间复杂度分析,假设root1的节点数为m.
<span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Arial, Helvetica, sans-serif;">root2的节点数为n.则最坏时间复杂度为O(m*n)</span>
<span style="font-family:Arial, Helvetica, sans-serif;">算法的步骤是这样子的:</span>
<span style="font-family:Arial, Helvetica, sans-serif;">遍历tree1 </span>
找与tree2 根节点相等的节点p2
每次找到p2.就检查以p2为根节点的子树是否与tree2相等,如果相等,就停止遍历
假设tree1 有k个节点值与tree1的根节点相等 则实际最坏时间复杂度为 O(m+k*n)
因而 时间效率还是可以接受的
<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
时间: 2024-09-29 05:53:02