AcWing 37. 树的子结构
原题链接
简单
作者:
小轩喵灬
,
2025-01-11 17:07:36
,
所有人可见
,
阅读 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasSubtree(TreeNode pRoot1, TreeNode pRoot2) {
if (pRoot1 == null || pRoot2 == null) {
return false;
}
return isSubtreeWithRoot(pRoot1, pRoot2) || hasSubtree(pRoot1.left, pRoot2) || hasSubtree(pRoot1.right, pRoot2);
}
private boolean isSubtreeWithRoot(TreeNode pRoot1, TreeNode pRoot2) {
if (pRoot2 == null) {
return true;
}
if (pRoot1 == null) {
return false;
}
if (pRoot1.val != pRoot2.val) {
return false;
}
return isSubtreeWithRoot(pRoot1.left, pRoot2.left) && isSubtreeWithRoot(pRoot1.right, pRoot2.right);
}
}