leecode每日一题03-subtree of another tree

题目描述:

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree scould also be considered as a subtree of itself.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2

Given tree t:

   4 
  / \
 1   2

Return true, because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

Given tree t:

   4
  / \
 1   2

Return false.

求解方法:

扫描二维码关注公众号,回复: 4788952 查看本文章
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool doesTree1hasTree2(TreeNode* tree1, TreeNode* tree2)
    {
        if(tree2 == NULL && tree1 == NULL)  return true;
        if(tree2 == NULL || tree1 == NULL)  return false;
        if(tree1->val == tree2->val)
        {
            return doesTree1hasTree2(tree1->left,tree2->left) && doesTree1hasTree2(tree1->right, tree2->right);
        }
        else
        {
            return false;
        }
    }
    bool isSubtree(TreeNode* s, TreeNode* t) 
    {
        bool res = false;
        if(t == NULL) res = true;
        if(s == NULL) res = false;
        
        if(s && t)
        {
            if(s->val == t->val)  
                res = doesTree1hasTree2(s,t); 
            if(res == false)
            {
                res = isSubtree(s->left,t);
            }
            if(res == false)
            {
                res = isSubtree(s->right,t);
            }            
        }  
        return res;
    }
};

小结:写这种递归问题时,最关键的是要搞清楚终止条件,使其可以满足不同情况,要不然很有可能在各种特殊case下出错。

猜你喜欢

转载自blog.csdn.net/qcxyliyong/article/details/83500859