面试题 04.10. 检查子树

Problem

T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1.

A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

Example1

Input: t1 = [1, 2, 3], t2 = [2]
Output: true

Example2

Input: t1 = [1, null, 2, 4], t2 = [3, 2]
Output: false

Solution

本题与面试题26. 树的子结构类似。

2020-3-6 递归解。从题目描述看,有更好的解法。

/**
 * 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 checkSubTree(TreeNode* t1, TreeNode* t2) {
        if(!t1 && !t2)
            return true;
        if(t1 && !t2)
            return true;
        if(!t1 && t2)
            return false;
        

        return dfs(t1,t2) || checkSubTree(t1->left,t2) || checkSubTree(t1->right,t2);

    }

    bool dfs(TreeNode* t1,TreeNode* t2)
    {
        if(!t1 && !t2)
            return true;
        if(t1 && !t2)
            return false;
        if(!t1 && t2)
            return false;
        if(t1->val != t2->val)
            return false;

        return dfs(t1->left,t2->left) && dfs(t1->right,t2->right);
    }
};
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104702528