树的子结构

引用剑指offer

 1 //判断以root1为根的树是否和树2有相同的结构(如果为真,必须从root1节点就相同)
 2 bool doesRoot1HaveAllNodesOfRoot2(treeNode* root1,treeNode* root2){
 3     if(root2==NULL)
 4         return true;
 5     if(root1==NULL)
 6         return false;
 7     if(root1->data!=root2->data)
 8         return false;
 9     return doesRoot1HaveAllNodesOfRoot2(root1->lChild,root2->lChild)&&
10         doesRoot1HaveAllNodesOfRoot2(root1->rChild,root2->rChild);
11 }
12 //判断是否为子结构
13 bool isSubStructure(treeNode* root1,treeNode* root2){
14     if(root2==NULL)
15         return true;
16     if(root1==NULL)
17         return false;
18     bool found=doesRoot1HaveAllNodesOfRoot2(root1,root2);
19     if(!found && root1->lChild!=NULL)
20         found=doesRoot1HaveAllNodesOfRoot2(root1->lChild,root2);
21     if(!found && root1->rChild!=NULL)
22         found=doesRoot1HaveAllNodesOfRoot2(root1->rChild,root2);
23     return found;
24 }

 

posted @ 2014-09-20 10:30  liuzhiminxd  阅读(132)  评论(0编辑  收藏  举报