using System ;
using System. Collections. Generic ;
namespace 剑指_Offer_26. _树的子结构
{
class Program
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode ( int x) { val = x; }
}
public static bool IsSubStructure ( TreeNode A, TreeNode B)
{
if ( A == null || B == null ) return false ;
return issub ( A, B) || IsSubStructure ( A. left, B) || IsSubStructure ( A. right, B) ;
}
static bool issub ( TreeNode A, TreeNode B)
{
if ( B == null ) return true ;
if ( A == null || A. val != B. val) return false ;
return issub ( A. left, B. left) && issub ( A. right, B. right) ;
}
static TreeNode creat ( )
{
TreeNode p;
int flag = Console. Read ( ) ;
if ( flag == '#' ) p = null ;
else
{
p = new TreeNode ( flag - 48 ) ;
p. left = creat ( ) ;
p. right = creat ( ) ;
}
return p;
}
static void Main ( string [ ] args)
{
TreeNode A = creat ( ) ;
TreeNode B = creat ( ) ;
Console. WriteLine ( IsSubStructure ( A, B) ) ;
}
}
}
要点
对于二叉树结构,递归往往是解决问题的最好思路 从根节点开始,看是否和B有相同的值和结构,然后看左右子数的根节点开始是否和B有相同的值和结构,只要其中之一符合则返回True 判断A是否包含B,从顶点开始判断值是否相同,然后继续判断A.left和B.left,A.right和B.right是否都相同,以此递归。当B为空时,表示B没有对应的结构,返回true,