树的子结构

//两棵二叉树判断B是不是A的子结构
//1.在A中遍历,找到节点与B根节点的值相等的节点
//2.对该节点和B树遍历,判断结构是否一样
//递归
#include<iostream>
using namespace std;

struct Node
{
    int value;
    Node* left;
    Node* right;
};
bool Traver(Node* pa, Node* pb)
{
    if (pb == NULL)
        return true;
    if (pa == NULL)
        return false;
    if (pa->value != pa->value)
        return false;
    return Traver(pa->left, pb->left) && Traver(pa->right, pb->right);
}

bool HasSubTree(Node* rootA, Node* rootB)
{
    bool has = false;
    while (rootA != NULL && rootB != NULL)
    {
        if (rootA->value == rootA->value)
            has = Traver(rootA, rootB);
        if (!has)
            HasSubTree(rootA->left, rootB);
        if (!has)
            HasSubTree(rootB->right, rootB);
    }
    return has;
}

你可能感兴趣的:(Leetcode,笔试题,二叉树,遍历)