1. Description of the topic
You are given two binary trees root and subRoot. Tests that root contains a subtree with the same structure and node values as subRoot. Returns true if present; otherwise, returns false.
A subtree of the binary tree tree includes a certain node of the tree and all descendant nodes of this node. tree can also be seen as a subtree of itself
Example one:
Example two:
2. Link to the original title
3. Thinking Analysis
Each subtree of root is compared with the tree of SubRoot
Code recursive expansion diagram:
4. Code implementation
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
//p q 都为空树
if( p== NULL && q ==NULL)
return true ;
//其中一个为空
if(p==NULL || q ==NULL)
return false ;
//都不为空
if(p->val !=q->val)
return false ;
//相等
return isSameTree(p->left , q->left)
&& isSameTree(p->right , q->right);
}
bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot)
{
//root为空树
if(root ==NULL)
return false ;
//root 不为空树
if( isSameTree (root ,subRoot))
return true ;
//递归
return isSubtree(root->left,subRoot)
|| isSubtree(root->right,subRoot);
}
If you think this article is helpful to you, you might as well move your fingers to like, collect and forward, and give Xi Ling a big attention. Every
support from you will be transformed into my motivation to move forward! !