输入两颗二叉树A,B,判断B是不是A的子结构。
#include<stdio.h> #include<iostream> using namespace std; struct BinaryTreeNode{ int value; BinaryTreeNode* left; BinaryTreeNode* right; }; //递归判断结点是否相等 bool doesTree1HasTree2(BinaryTreeNode* aRoot,BinaryTreeNode* bRoot){ if(bRoot==NULL{ return true; } if(aRoot==NULL){ return false; } if(aRoot->value!=bRoot->value){ return false; } return doesTree1HasTree2(aRoot->left,bRoot->left)&&doesTree1HasTree2(aRoot->right,bRoot->right); } ListNode* hasSubtree(BinaryTreeNode* aRoot,BinaryTreeNode* bRoot){ bool result = false; if(aRoot!=NULL&&bRoot!=NULL){ if(aRoot->value==bRoot->value){ result = doesTree1HasTree2(aRoot,bRoot); } if(!result){ result = hasSubtree(aRoot->left,bRoot); } if(!result){ result = hasSubtree(aRoot->right,bRoot); } } return result; } int main(){ return 0; }
时间: 2024-10-13 03:15:44