您的位置:首页 > 职场人生

剑指offer 面试题18 判断二叉树B是否是A的子结构

2014-12-23 16:44 531 查看
struct BinaryTreeNode{
int data;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
//find a A-node that equals B-root,send it to the core func
//judge:root--left--right,and recursion
bool SubTree(BinaryTreeNode *pRootA,BinaryTreeNode *pRootB){
bool result=false;
if(pRootA==NULL||pRootB==NULL)
return result;
if(pRootA->data==pRootB->data)
result=SubTree_core(pRootA,pRootB);
//which means rootA->data=rootB->data,but not all nodes
if(!result)
result=SubTree(pRootA->left,pRootB);
if(!result)
result=SubTree(pRootA->right,pRootB);
return result;
}
//get 2 trees whose roots are equal
//judge whether A-Node always equal B-node till B-null
bool SubTree_core(BinaryTreeNode *pRootA,BinaryTreeNode *pRootB){
if(pRootB==NULL)
return true;
if(pRootA==NULL)
return false;
if(pRootA->data!=pRootB->data)
return false;
return SubTree_core(pRootA->left,pRootB->left)&&
SubTree_core(pRootA->right,pRootB->right);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: