15-- 输入两个二叉树A和B,判断B树是否包含于A树。
// // main.cpp // subStructureInTree // // Created by Hugo Cao on 15/7/10. // Copyright (c) 2015年 Hugo Cao . All rights reserved. // /* 问题描述: 输入两个二叉树A和B,判断B树是否包含于A树。 查找B子树是否在A中, 思路:(1)首先寻找B根结点,是否在A中, (2)如果在,就查看是否A树包含B树 思考如何遍历A树寻找更结点,因为只有前序遍历可以最先找到根节点 */ #include <iostream> using namespace std; #define Data int typedef struct binaaryTreeNode { Data m_value; binaaryTreeNode *m_plift; binaaryTreeNode *m_pright; }btNode, *binTree; binTree addNode(Data value) { binTree bt = NULL; bt = new btNode; if (bt == NULL) { cout << "申请地址错误" << endl; return NULL; } bt->m_value = value; bt->m_plift = NULL; bt->m_pright = NULL; return bt; } bool connectTreeNode(binTree parrentNode, binTree leftSonNode = NULL, binTree rightSonNode = NULL) { if (parrentNode == NULL || (leftSonNode == NULL && rightSonNode == NULL)) { cout << "结点输入问题" << endl; return false; } parrentNode->m_plift = leftSonNode; parrentNode->m_pright = rightSonNode; return true; } binTree createBinaryATree(binTree Ahead) { binTree p1 = addNode(8); binTree p2 = addNode(8); binTree p3 = addNode(7); binTree p4 = addNode(9); binTree p5 = addNode(2); binTree p6 = addNode(4); binTree p7 = addNode(7); connectTreeNode(p1, p2, p3); connectTreeNode(p2, p4, p5); connectTreeNode(p5, p6, p7); return (Ahead = p1); } binTree createBinaryBTree(binTree Ahead) { binTree p1 = addNode(8); binTree p2 = addNode(9); binTree p3 = addNode(2); connectTreeNode(p1, p2, p3); return (Ahead = p1); } void RLR_print_BinaryTree(binTree bt) { if (bt == NULL) return ; cout << bt->m_value << " " << endl; RLR_print_BinaryTree(bt->m_plift); RLR_print_BinaryTree(bt->m_pright); } //判断是否为包含关系。 bool DoesTree1HaveTree2(binTree p1, binTree p2) { //树2为空是可以的, if (p2 == NULL) return true; //树2不为空,树1为空,就是证明1树没有包含2树 if (p1 == NULL) return false; //都不为空,判断值是否相同。不相同返回错误。 if (p1->m_value != p2->m_value) return false; //递归调用,保证左右子树都包含在A树中,才可以证明是A树包含B树。 return DoesTree1HaveTree2(p1->m_plift, p2->m_plift) && DoesTree1HaveTree2(p1->m_pright, p2->m_pright); } //判断是否是子树, 先寻找和B树相同的根结点。 bool findSubTree(binTree point1, binTree point2) { bool result = false; //这里递归调用point2,一直都没有改变,point1在不停的递归。 if (point1 != NULL && point2 != NULL) { //查找到了子B树根节点存在于要查找的A树中,开始进行比对 if (point1->m_value == point2->m_value) result = DoesTree1HaveTree2(point1, point1); //没有找到就继续寻找左子树 if (!result) result = findSubTree(point1->m_plift, point2); //没有找到就继续寻找右子树 if (!result) result = findSubTree(point1->m_pright, point2); } return result; } int main() { binTree bt_A = NULL; bt_A = createBinaryATree(bt_A); RLR_print_BinaryTree(bt_A); cout << endl; binTree bt_B = NULL; bt_B = createBinaryBTree(bt_B); RLR_print_BinaryTree(bt_B); cout << endl; if (true == findSubTree(bt_A, bt_B)) cout << "是子树" << endl; else{ cout << "不是子树" << endl; } return 0; }