题目
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
题解
先找出A中val等于B树根节点的val的节点。然后以该节点为根节点,与B树进行比较。相同就返回true,否则继续遍历A树,然后重复上述操作。如果A遍历完了都没有匹配到,则为false。
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
/*
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(pRoot2==null || pRoot1==null)
{
return false;
}
return FindChild( pRoot1, pRoot2);
}
public bool FindChild(TreeNode tree1,TreeNode tree2)
{
Stack<TreeNode> stack=new Stack<TreeNode>();
while(stack.Count>0 || tree1!=null)
{
if(tree1!=null)
{
if(tree1.val==tree2.val)
{
if(CanFind(tree1,tree2))
return true;
}
stack.Push(tree1);
tree1=tree1.left;
}
else
{
tree1=stack.Pop();
tree1=tree1.right;
}
}
return false;
}
public bool CanFind(TreeNode tree1,TreeNode tree2)
{
if(tree2==null)
return true;
if(tree1==null)
return false;
if(tree1.val!=tree2.val)
return false;
return CanFind(tree1.left,tree2.left) && CanFind(tree1.right,tree2.right);
}
}