题解
- 先序遍历树1,判断树1以每一个节点为根的子树是否包含树2的拓扑结构。
- 时间复杂度:O(M*N)
- 注意区分判断整体包含关系、和判断子树是否包含树2的函数。
代码
public class Main {
public static void main(String args[]) {
//test
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
n1.left=n2;
n1.right=n3;
n3.left=n4;
Node n5=new Node(3);
Node n6=new Node(4);
n5.left=n6;
if(contains(n1,n5)) {
System.out.print("contains");
}
else {
System.out.print("not contains");
}
}
public static boolean contains(Node root,Node rootTest) {
if(rootTest==null) {
return true;
}
if(root==null) {
return false;
}
return check(root,rootTest)||contains(root.left,rootTest)||contains(root.right,rootTest);
}
public static boolean check(Node root,Node rootTest) {
if(rootTest==null) {
return true;
}
if(root==null||root.val!=rootTest.val) {
return false;
}
return check(root.left,rootTest.right)&&check(root.right,rootTest.right);
}
}