leetcode-剑指26-OK

// language c
// 剑指26
// https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
// 绕了半天才搞出来,由于本人c基础薄弱,只能想出用链表来动态存储地址的低效存储方案,以后没事干可优化
/**


 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

 struct Node {
     struct TreeNode *address;
     struct Node *next;
 }Node;

Node* makenode(){
    Node * one = (Node*)malloc(sizeof(Node));
    one->address = NULL;
    one->next = NULL;
}

void filladdress(Node* one,struct TreeNode* address){
    one->address = address;
}

void fillnext(Node* one,Node *next){
    one->next = next;
}

bool isSubStructure(struct TreeNode* A, struct TreeNode* B){
    if(B==NULL)
        return false;

    // 找到B的根在A中的位置的节点的地址,假设A中所有结点的值不同,假设错误,懒得改了,先快活快活,快活完了,继续
    // 此函数用于寻找
    Node *first = NULL;
    Node *temp;
    void findNode(struct TreeNode* root, int x){
        if(root == NULL)
            return;
        if(root->val == x){
            temp = makenode();
            filladdress(temp,root);
            fillnext(temp,first);
            first = temp;
            return;
        }
        struct TreeNode * left = findNode(root->left,x);
        struct TreeNode * right = findNode(root->right,x);
        if(left){
            temp = makenode();
            filladdress(temp,root);
            fillnext(temp,first);
            first = temp;
            return;
        }
        if(right){
            temp = makenode();
            filladdress(temp,root);
            fillnext(temp,first);
            first = temp;
            return;
        }
        return;
    }

    bool AbaohanB(struct TreeNode* A, struct TreeNode* B){
        if((A==NULL)&&(B==NULL))
            return true;
        if((A==NULL)||(B==NULL))
            return false;
        if(A->val != B->val)
            return false;
        bool left,right;
        if(B->left)
            left = AbaohanB(A->left,B->left);
        else
            left = true;
        if(B->right)
            right = AbaohanB(A->right,B->right);
        else right = true;
        if(left&&right)
            return true;
        return false;
    }
    
    struct TreeNode* C;
    findNode(A,B->val);
    temp = first;
    while(first){
        C = first->address;
        if(AbaohanB(A,C))
            return true;
        first = first->next;
    }
    free (temp);
    // 最后没找到就false;
    return false;
}
posted @ 2021-01-28 04:39  RougeBW  阅读(43)  评论(0编辑  收藏  举报