剑指 Offer 26. 树的子结构(Sword finger offer 26 Substructure of tree)

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

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

例如:
给定的树 A:


     3
    / \
   4   5
  / \
 1   2

给定的树 B:


   4 
  /
 1

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

递归

class Solution {
    public boolean isSubStructure(TreeNode root1, TreeNode root2) {
        return (root1 != null && root2 != null) && (isSame(root1, root2) || isSubStructure(root1.left, root2) || isSubStructure(root1.right, root2));
    }

    public boolean isSame(TreeNode root1, TreeNode root2) {
        if (root2 == null) {
            return true;
        }
        if (root1 == null) {
            return false;
        }
        return root1.val == root2.val && isSame(root1.left, root2.left) && isSame(root1.right, root2.right);
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

————————

Input two binary trees a and B to judge whether B is the substructure of A. (the contract empty tree is not a substructure of any tree)

B is the substructure of a, that is, the same structure and node values as B appear in a.

For example:
Given tree A:


     3
    / \
   4   5
  / \
 1   2

Given tree B:


   4 
  /
 1

Returns true because a subtree of B and a has the same structure and node values.

Source: leetcode
Link: https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

recursion

class Solution {
    public boolean isSubStructure(TreeNode root1, TreeNode root2) {
        return (root1 != null && root2 != null) && (isSame(root1, root2) || isSubStructure(root1.left, root2) || isSubStructure(root1.right, root2));
    }

    public boolean isSame(TreeNode root1, TreeNode root2) {
        if (root2 == null) {
            return true;
        }
        if (root1 == null) {
            return false;
        }
        return root1.val == root2.val && isSame(root1.left, root2.left) && isSame(root1.right, root2.right);
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}