[LeetCode] 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.

判断t是否为s的子树。首先这是一个判断一棵数的子树是否与另一棵树相同,则使用一个判断两树是否相同的函数,然后将s的每一个节点的子树与t比较,相同则返回true,否则返回false。

class Solution {
public:
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if (s == nullptr)
            return false;
        if (isSameTree(s, t))
            return true;
        return isSubtree(s->left, t) || isSubtree(s->right, t);
    }
    bool isSameTree(TreeNode* s, TreeNode* t) {
        if (s == nullptr && t == nullptr)
            return true;
        if (s == nullptr || t == nullptr)
            return false;
        if (s->val == t->val)
            return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
        return false;
    }
};
// 25 ms

先对两棵树进行先序遍历,注意的是先序遍历的时候需要在节点值前加入’#‘以区分节点值,并注意区分叶节点的左”lnull“右”rnull“空指针。并将先序遍历的结果放在一个字符串中,然后对两个字符串进行模式匹配。由于文本串和模式串都比较小,所以使用简单的基于蛮力算法的模式匹配算法。

class Solution {
public:
    bool isSubtree(TreeNode* s, TreeNode* t) {
        string tree1 = preOrder(s, true);
        string tree2 = preOrder(t, true);
        return match(tree1, tree2);
    }
    string preOrder(TreeNode* root, bool left) {
        if (root == nullptr) {
            if (left)
                return "lnull";
            else
                return "rnull";
        }
        return "#" + to_string(root->val) + " " + preOrder(root->left, true) + " " + preOrder(root->right, false);
    }
    bool match(string s1, string s2) {
        int n = s1.size(), m = s2.size();
        int i = 0, j = 0;
        while (j < m && i < n) {
            if (s2[j] == s1[i]) {
                i++;
                j++;
            }
            else {
                i -= (j - 1);
                j = 0;
            }
        }
        if (j == m)
            return true;
        else
            return false;
    }
};
// 42 ms

 

posted @ 2017-07-21 17:19  immjc  阅读(159)  评论(0编辑  收藏  举报