题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
解题思路
首先对A进行前序遍历,如果A的当前节点和B的根节点相等,则对A的当前位置和B的根位置遍历所有节点判断是否相等。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class shudezijiegou {
public boolean findSub(TreeNode root1, TreeNode root2) {
if (root2 == null)
return true;
if (root1 == null)
return false;
if (root1.val != root2.val)
return false;
return findSub(root1.left, root2.left) && findSub(root1.right, root2.right);
}
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
if (root2 == null || root1 == null)
return false;
if (root1.val == root2.val) {
if (findSub(root1, root2))
return true;
}
if (HasSubtree(root1.left, root2))
return true;
if (HasSubtree(root1.right, root2))
return true;
return false;
}
public static void main(String[] args) {
TreeNode node = new TreeNode(2);
TreeNode n = new TreeNode(8);
node.left = n;
n.left = new TreeNode(1);
n.right = new TreeNode(2);
TreeNode node1 = new TreeNode(8);
node1.left = new TreeNode(1);
node1.right = new TreeNode(2);
System.out.println(new shudezijiegou().HasSubtree(node, node1));
}
}