【Lintcode|leetcode】245 Subtree

<span style="font-family: Arial, Helvetica, sans-serif;">/**</span>
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param T1, T2: The roots of binary tree.
     * @return: True if T2 is a subtree of T1, or false.
     */
    bool isSubtree(TreeNode *T1, TreeNode *T2) {
        // write your code here
       if(T1==nullptr&&T2==nullptr)return true;
       if(T1==nullptr)return false;
       if(T2==nullptr)return true;
       if(isIdentical(T1,T2))return true;
       return (isSubtree(T1->left,T2)||isSubtree(T1->right,T2));
    }
    
    bool isIdentical(TreeNode* t1,TreeNode* t2){
        if(t1==nullptr&&t2==nullptr)return true;
         if(t1==nullptr && t2 != nullptr)
            return false;
         if(t1!=nullptr && t2 == nullptr)
            return false;
        if(t1->val==t2->val){
         return isIdentical(t1->left,t2->left)&&isIdentical(t1->right,t2->right);
        }
        else
          return false;
    }
};
 
 

题意:通过递归判断T1中以每一个节点作为根节点的子树是否和T2等价,若等价,返回true,否则返回false.

注意点:递归出口一定要写清楚,

 if(T1==nullptr)return false;
  if(T2==nullptr)return true;
这两句是为了保证后面出现的T1->left T1->right的合法性

你可能感兴趣的:(LeetCode,lintcode)