一、题目描述
输入两棵二叉树A和B,判断B是不是A的子结构例如:
8 --- 二叉树A
/ \
8 7
/ \
9 2
/ \
4 7
---------------------------------
8 --- 二叉树B
/ \
9 2
则二叉树B是A的子结构
二、解题思路
本题主要考察二叉树的遍历
二叉树A中, 8/ \
8 7
根节点与二叉树B的根节点相同,则继续观察左右结点的值是否相同,发现不同,则递归分别遍历二叉树A的左子树和右子树,观察左子树或右子树的根节点与B二叉树是否相同,以此类推
因此这里涉及到两个递归
1是遍历A二叉树的递归
2是对目标子A二叉树与B二叉树左右子树值判等的递归
三、解题算法
/***************************************************************
Author:tmw
date:2018-6-30
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct BiTreeNode
{
int data;
struct BiTreeNode* lchild;
struct BiTreeNode* rchild;
}BiTreeNode;
/**
* 遍历子二叉树A的左右子树是否与B的左右子树匹配
* @param *TreeRootA
* @param *TreeRootB
*
* 注:本代码未经测试,看逻辑就好
*/
bool SubTreeA_equal_TreeB( BiTreeNode* TreeRootA, BiTreeNode* TreeRootB )
{
/**递归出口**/
if( TreeRootB == NULL )
return true;
if( TreeRootA == NULL )
return false;
if( TreeRootA->data != TreeRootB->data )
return false;
return SubTreeA_equal_TreeB(TreeRootA->lchild, TreeRootB->lchild)
&& SubTreeA_equal_TreeB(TreeRootA->rchild, TreeRootB->rchild);
}
/**遍历二叉树A的根节点是否与二叉树B根节点相同
* @param *TreeRootA
* @param *TreeRootB
*/
bool hasSubTree( BiTreeNode* TreeRootA, BiTreeNode* TreeRootB )
{
/**入参检查**/
if( TreeRootA == NULL || TreeRootB == NULL ) return false;
bool result = false;
/**算法执行**/
if( TreeRootA != NULL && TreeRootB != NULL )
{
/**当根结点相等时,则SubTreeA_equal_TreeB()函数递归找左右子树是否也匹配**/
if( TreeRootA->data == TreeRootB->data )
result = SubTreeA_equal_TreeB( TreeRootA, TreeRootB );
if( result == false )/**没找着,递归遍历A的左子树**/
hasSubTree(TreeRootA->lchild, TreeRootB);
if( result == false )/**左子树没找着找找右子树**/
hasSubTree(TreeRootA->rchild, TreeRootB);
}
return result;
}
梦想还是要有的,万一实现了呢~~~ヾ(◍°∇°◍)ノ゙~~~~