树的子结构



// .cpp :

//

#include "stdafx.h"

#include <queue>

using namespace std;

typedef struct binary_tree

{

int val;

binary_tree* left;

binary_tree* right;

}BINARY_TREE;

BINARY_TREE* tree = NULL;

BINARY_TREE* subtree = NULL;

void create_binatree_node(BINARY_TREE** ptr, int v)

{

BINARY_TREE* ptr1 = new BINARY_TREE;

ptr1->val = v;

ptr1->left = NULL;

ptr1->right = NULL;

*ptr = ptr1;

}

void create_binatree()

{

tree = new BINARY_TREE;

tree->val = 8;

tree->left = NULL;

tree->right = NULL;

BINARY_TREE* ptr = tree;

create_binatree_node(&(ptr->left),8);

create_binatree_node(&(ptr->right),7);

ptr = ptr->left;

create_binatree_node(&(ptr->left),9);

create_binatree_node(&(ptr->right),2);

ptr = ptr->right;

create_binatree_node(&(ptr->left),4);

create_binatree_node(&(ptr->right),7);

}

void create_sub_binatree()

{

subtree = new BINARY_TREE;

subtree->val = 8;

subtree->left = NULL;

subtree->right = NULL;

BINARY_TREE* ptr = subtree;

create_binatree_node(&(ptr->left),9);

create_binatree_node(&(ptr->right),2);

}

void print_layer()

{

queue<BINARY_TREE*> s;

BINARY_TREE* ptr = tree;

s.push(ptr);

ptr = s.front();

while(ptr != NULL)

{

printf("%d ", ptr->val);

if (ptr->left != NULL)

{

s.push(ptr->left);

}

if (ptr->right != NULL)

{

s.push(ptr->right);

}

s.pop();

if (!s.empty())

{

ptr = s.front();

}

else

{

ptr = NULL;

}

}

printf("\n");

}

int match(BINARY_TREE* tree, BINARY_TREE* subtree)

{

if ( NULL != tree && NULL != subtree)

{

if (tree->val == subtree->val)

{

int ret1 = match(tree->left, subtree->left);

int ret2 = match(tree->right, subtree->right);

return ret1 & ret2;

}

else

{

return 0;

}

}

else if ( NULL == tree && NULL == subtree )

{

return 1;

}

else if ( NULL != tree && NULL == subtree )

{

return 1;

}

else

{

return 0;

}

}

int print_pre_order(BINARY_TREE* ptr)

{

if (NULL == ptr)

{

return 0;

}

int ret = match(ptr, subtree);

printf("%d ", ret);

if (1 == ret)

{

return 1;

}

if ( 1 == print_pre_order(ptr->left))

{

return 1;

}

if (1 == print_pre_order(ptr->right))

{

return 1;

}

return 0;

}

int _tmain(int argc, _TCHAR* argv[])

{

create_binatree();

create_sub_binatree();

//print_layer();

print_pre_order(tree);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值