题目:
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:
1.创建一个方法用于判定当前节点是不是子树,递归思路
2.主函数先判定当前节点是否为子树,不是则依次比较左右子树
代码:
/*
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode (int x)
{
val = x;
}
}*/
class Solution
{
public bool HasSubtree(TreeNode pRoot1, TreeNode pRoot2)
{
// write code here
if(pRoot1==null || pRoot2==null)
return false;
bool flag = false;
flag = IsSubtree(pRoot1,pRoot2);
if(!flag)
flag = HasSubtree(pRoot1.left,pRoot2);
if(!flag)
flag = HasSubtree(pRoot1.right,pRoot2);
return flag;
}
public bool IsSubtree(TreeNode pRoot1, TreeNode pRoot2)
{
if(pRoot2 == null)
return true;
if(pRoot1 == null)
return false;
if(pRoot1.val != pRoot2.val)
return false;
return IsSubtree(pRoot1.left, pRoot2.left) && IsSubtree(pRoot1.right, pRoot2.right);
}
}