题目描述:
思路:首先遍历A树,找到A树中等于B树根节点的结点,之后以该节点为起始节点,检查B树是否为A树的子结构。要注意一点,题目中没说每个结点的值唯一,因此不能一找到A树种等于B树根节点的结点就停止,而是需要先判断如果相等则停止,否则继续向下寻找A树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if(B==null)return false;
if(A==null)return false;
return subStructure(A,B)||isSubStructure(A.left,B)||isSubStructure(A.right,B);
}
public boolean subStructure(TreeNode A, TreeNode B){
if(B==null)return true;
if(A==null||A.val!=B.val)return false;
return subStructure(A.left,B.left)&&subStructure(A.right,B.right);
}
}