题目:树的子结构
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
首先需要递归pRoot1树,找到与pRoot2根一样的节点;
找到相同的根节点后,再递归遍历pRoot1和pRoot2的左右节点,判断其结构是否一致。
参考代码
/*
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
bool result = false;
if(pRoot1 != null && pRoot2 != null)
{
if(pRoot1.val == pRoot2.val)
result = DoesTree1HaveTree2(pRoot1,pRoot2);
if(result == false)
result = HasSubtree(pRoot1.left,pRoot2);
if(result == false)
result = HasSubtree(pRoot1.right,pRoot2);
}
return result;
}
public bool DoesTree1HaveTree2(TreeNode pRoot1,TreeNode pRoot2)
{
if(pRoot2 == null)
return true;
if(pRoot1 == null)
return false;
if(pRoot1.val != pRoot2.val)
return false;
return DoesTree1HaveTree2(pRoot1.left,pRoot2.left) && DoesTree1HaveTree2(pRoot1.right,pRoot2.right);
}
}