Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[剑指 Offer] 26. 树的子结构 #42

Open
frdmu opened this issue Jul 28, 2021 · 0 comments
Open

[剑指 Offer] 26. 树的子结构 #42

frdmu opened this issue Jul 28, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 28, 2021

输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)

B是A的子结构, 即 A中有出现和B相同的结构和节点值。

例如:
给定的树 A:

     3
    /
   4   5
  /
 1   2
给定的树 B:

   4 
  /
 1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。

示例 1:

输入:A = [1,2,3], B = [3,1]
输出:false

示例 2:

输入:A = [3,4,5,1,2], B = [4,1]
输出:true

限制:

  • 0 <= 节点个数 <= 10000

解法:
解决这道题,总共分两步:
1.在A中找到值等于B->val的节点tmp;
2.判断以tmp为根的树是否包含B。
代码如下:

/**
 * 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 check(TreeNode* A, TreeNode* B) {
        if (B && !A) return false; 
        if (!B) return true;
        
        if (A->val == B->val) {
            return check(A->left, B->left) && check(A->right, B->right);
        }
        return false;
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if (!B) return false;
        
        queue<TreeNode*> q;
        
        q.push(A); 
        while(!q.empty()) {
            TreeNode* tmp = q.front();
            q.pop();
            if (tmp->val == B->val) {
                if (check(tmp, B)) {
                    return true;
                }
            }        
            if (tmp->left)
                q.push(tmp->left);
            if (tmp->right)
                q.push(tmp->right);    
        }
        
        return false;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant