#include <iostream> #include <queue> using namespace std; struct treenode{ int value; Treenode* left; treenode* right; treenode* parent;};/ /node structure 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; }
Here is the relevant code <strong>bool Issametree (treenode* root1,treenode*root2) {if (root2==null&&root1==null)// Two equals NULL return true;if (root1==null| | Root2==null)//Only one equals 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); }
Time complexity analysis, assuming that the number of nodes in ROOT1 is M.
<span style= "font-family:arial, Helvetica, Sans-serif;" > </span><span style= "font-family:arial, Helvetica, Sans-serif;" >root2 the number of nodes is N. The worst time complexity is O (m*n) </span>
<span style= "font-family:arial, Helvetica, Sans-serif;" The steps of the > algorithm are such:</span>
<span style= "font-family:arial, Helvetica, Sans-serif;" > Traverse tree1 </span>
Find the node that is equal to the Tree2 root node p2
Every time I find P2. Checks if the subtree with P2 as the root node is equal to Tree2, and if it is equal, stops traversing
Assuming that the tree1 has a K node value equal to the root node of the tree1, the actual worst time complexity is O (m+k*n)
So time efficiency is still acceptable.
<span style= "font-family:arial, Helvetica, Sans-serif;" > </span>
How to tell if a binary tree tree is a subtree of another binary tree