树的子结构(剑指offer18)

题目:输入两棵二叉树A和B,判断B是不是A的子结构。二叉树的结点定义如下:

struct BinaryTreeNode {
	int m_nValue;
	BinaryTreeNode* m_pLeftChild;
	BinaryTreeNode* m_pRightChild;
};

思路:判断B是不是A的子树,先判断树B的根是否与A树的某子树的根结点是否一致,我们可以通过遍历二叉树数A的每一个结点,比较其是否与树B的根结点一样。如果找到满足添加的结点,我们分别比较其左右子树的根结点是否一致,可以利用递归重复上一步骤。

//有两棵二叉树A、B,判断B是否是A的子树
bool isSubTree(BinaryTreeNode* pRootA, BinaryTreeNode* pRootB) {
	bool result = false;
	if (NULL == pRootA || NULL == pRootB) {
		return result;
	}

	//判断根结点是否一致
	if (pRootA->m_nValue == pRootB->m_nValue) {
		result = isAHasSubTreeB(pRootA, pRootB);
	}

	//如果根结点不一致,则比较与左子树的根是否一致
	if (!result) {
		result = isAHasSubTreeB(pRootA->m_pLeftChild, pRootB);
	}

	//如果左子树也不一致,则比较与右子树的根是否也一致
	if (!result) {
		result = isAHasSubTreeB(pRootA->m_pRightChild, pRootB);
	}

	return result;
}

//判断其子树是否满足条件
bool isAHasSubTreeB(BinaryTreeNode* pRootA, BinaryTreeNode* pRootB) {
	//如果B树没有结点
	if (NULL == pRootB) {
		return true;
	}

	//如果B有结点而A没有对应的结点
	if (NULL == pRootA) {
		return false;
	}

	//判断根结点是否一致
	if (pRootA->m_nValue != pRootB->m_nValue) {
		return false;
	}

	//递归判断左右子树
	return isAHasSubTreeB(pRootA->m_pLeftChild, pRootB->m_pLeftChild)
			&& isAHasSubTreeB(pRootA->m_pRightChild, pRootB->m_pRightChild);
}

测试代码

/*
 *
 *  Created on: 2014-3-23 15:13:11
 *      Author: danDingCongRong
 */

#include <stddef.h>
#include <iostream>

using namespace std;

int main() {
	int n = 0;
	cout << "输入测试数据的组数:" << endl;
	cin >> n;
	while (n) {
		cout << "按先序序列创建二叉树:" << endl;
		BinaryTreeNode* pABinaryTree = NULL;
		pABinaryTree = createIntBinaryTree();

		cout << "按先序序列创建二叉树:" << endl;
		BinaryTreeNode* pBBinaryTree = NULL;
		pBBinaryTree = createIntBinaryTree();

		bool result = isSubTree(pABinaryTree, pBBinaryTree);
		if (result) {
			cout << "B是A的子结构。" << endl;
		} else {
			cout << "B不是A的子结构。" << endl;
		}

		--n;
	}

	return 0;
}

注:部分内容参考自剑指offer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值