[LeetCode] 572、另一个树的子树

题目描

给定两个非空二叉树 st,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。

给定的树 s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

给定的树 t:

   4
  / \
 1   2

返回 false

解题思路

与《剑指offer》第26题稍有不同。

参考代码

// 递归遍历树
class Solution {
     
public:
    bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
     
        if(pRoot1 == nullptr || pRoot2 == nullptr)
            return false;
        
        bool res = false;  // 默认值(重要)
        if(pRoot1->val == pRoot2->val)
            res = hasSubTreeRecusively(pRoot1, pRoot2);
        if(!res)
            res = isSubtree(pRoot1->left, pRoot2);
        if(!res)
            res = isSubtree(pRoot1->right, pRoot2);
        return res;
    }
    
    bool hasSubTreeRecusively(TreeNode* pRoot1, TreeNode* pRoot2){
     
        if(pRoot1 == nullptr && pRoot2 == nullptr)
            return true;
        if(pRoot1 == nullptr || pRoot2 == nullptr)
            return false;
        
        if(pRoot1->val != pRoot2->val)
            return false;
            
        return hasSubTreeRecusively(pRoot1->left, pRoot2->left) &&
               hasSubTreeRecusively(pRoot1->right, pRoot2->right);
    }
    
};

你可能感兴趣的:(算法(UVa,+,LeetCode,+,OJ,+,……))