AcWing 37. 树的子结构-java
原题链接
简单
作者:
jkm
,
2021-03-29 12:41:13
,
所有人可见
,
阅读 270
树的子结构(java递归实现)
/**
* 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;
if (isPart(pRoot1, pRoot2))
return true;
return hasSubtree(pRoot1.left, pRoot2) || hasSubtree(pRoot1.right, pRoot2);
}
private boolean isPart(TreeNode pRoot1, TreeNode pRoot2) {
if (pRoot2 == null)
return true;
if (pRoot1 == null || pRoot1.val != pRoot2.val)
return false;
return isPart(pRoot1.left, pRoot2.left) && isPart(pRoot1.right, pRoot2.right);
}
}