题目描述
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:
给定的树 s:
3
/ \
4 5
/
1 2
给定的树 t:
4
/
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
示例 2:
给定的树 s:
3
/ \
4 5
/
1 2
/
0
给定的树 t:
4
/
1 2
返回 false。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtree-of-another-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 这个题目与剑指 offer的基本上一样,区别在于题目给定的示例2,在剑指 offer中返回true,在leetcode中返回false。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null || t == null) return false;
if(!isSameTree(s, t)){
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
return true;
}
private boolean isSameTree(TreeNode root1,TreeNode root2){
if(root1 == null && root2 == null) return true;
// 这里是与剑指 offer不同的地方
if(root1 == null || root2 == null) return false;
if(root1.left == null && root2.left == null && root1.right == null && root2.right == null){
if(root1.val == root2.val) return true;
return false;
}
if(root1.val == root2.val){
return isSameTree(root1.left, root2.left) && isSameTree(root1.right, root2.right);
}
return false;
}
}