牛客网-剑指Offer-树的子结构

题目链接:https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

先特判空树情况,然后使用递归的方法。

一、如果A和B的当前节点值相等,可以有三种选择:

  1. A、B树均继续遍历左右节点,且两树左节点和右节点均必须相等。

  2. B树回到根节点,继续遍历A的左子树。

  3. B树回到根节点,继续遍历B的右子树。

二、如果当前节点值不相等,有两种选择,即一中的2、3

  1. B树回到根节点,继续遍历A的左子树。
  2. B树回到根节点,继续遍历B的右子树。

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     bool dfs(TreeNode* pRoot1, TreeNode* pRoot2)
13     {
14         if(pRoot2 == NULL)
15             return true;
16         
17         if(pRoot1 == NULL && pRoot2 != NULL)
18             return false;
19         
20         if(pRoot1->val == pRoot2->val)
21             return dfs(pRoot1->left, pRoot2->left) && dfs(pRoot1->right, pRoot2->right)
22             || dfs(pRoot1->left, pRoot2) || dfs(pRoot1->right, pRoot2);
23         
24         return dfs(pRoot1->left, pRoot2) || dfs(pRoot1->right, pRoot2);
25     }
26     
27     bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
28     {
29         if(pRoot1 == NULL || pRoot2 == NULL)
30             return false;
31         return dfs(pRoot1, pRoot2);
32     }
33 };
View Code

猜你喜欢

转载自www.cnblogs.com/westwind1005/p/10140564.html