MOOC Zhejiang University Data Structure-04-Tree 4 Is the same binary search tree (25 points)

Although I listened to the lecture of the teacher in the MOOC, it was still very difficult to write this topic. I am not very familiar with trees and recursion. I am not very familiar with the application of the flag variable flag. When writing a function with recursion, I don't know when to return. Reference blog: 04-Tree 4 is the same binary search tree (25 points)

#include<stdio.h>
#include<stdlib.h> //malloc
//使用链表存储二叉搜索树
typedef struct TreeNode *Tree;
struct TreeNode{
    
    
    int Data;
    Tree Left,Right;
    int flag;
};
//新建一个节点,动态分配节点,向节点存入数据
Tree NewNode(int v){
    
    
    Tree T;
    T = (Tree)malloc(sizeof(struct TreeNode));
    T->Data = v;
    T->Left = NULL;
    T->Right = NULL;
    return T;
}
//向树中插入节点的函数
Tree Insert(Tree T,int v){
    
     
    if(!T) T = NewNode(v); //当传入的T为空时。错写成return NewNode(v)
    else if(v>T->Data){
    
    
        T->Right = Insert(T->Right,v);
    }
    else if(v<T->Data){
    
    
        T->Left = Insert(T->Left,v);
    }
    return T;
}
Tree BuildTree(int N){
    
    
    int v;
    Tree T = NULL;
    for(int i=0;i<N;++i){
    
    
        scanf("%d",&v);
        T = Insert(T,v);
    }
    return T;
}
//check if the value v is legal(合法)
int check(Tree T,int v){
    
    
	//check是对一个节点进行判断,judge是对一行数据进行判断
    // int flag=0;  //should not define the flag 
    //flag的值为1代表该节点被访问过了,值为0代表没有被访问过
    if(T->flag){
    
    //wrong used T->Data!=v
        if(T->Data>v){
    
    
            return check(T->Left,v);//forget return
        }
        else if(T->Data<v){
    
    
            return check(T->Right,v);
        }
        else{
    
    
            return 0;
        }
    }
    else{
    
    
        if(T->Data==v){
    
    //wrong used !flag
            T->flag=1;
            return 1;
        }
        else return 0;
    }
}
int judge(Tree T,int N){
    
    //一个judge函数读入一行数据,判断这一行(这棵树)是否是同一棵二叉搜索树
    int v,signal=1;
    //signal为1代表是同一棵二叉搜索树,为0代表不是
    for(int i=0;i<N;++i){
    
    
        scanf("%d",&v);
        if(signal && !check(T,v)){
    
    
            signal = 0;
        }
    }
    if(signal) return 1;
    else return 0;
}
void Reset(Tree T){
    
    
    if(T->Left) Reset(T->Left);//forget the if 
    if(T->Right) Reset(T->Right);
    T->flag = 0;
}
void Free(Tree T){
    
    
    if(T->Left) Free(T->Left);
    if(T->Right) Free(T->Right);
    free(T);
}
int main(){
    
    
    int N,L;
    Tree T;
    scanf("%d",&N);
    while(N){
    
    
        scanf("%d",&L);
        T = BuildTree(N);
        for(int i=0;i<L;++i){
    
    
            if(judge(T,N)){
    
    
                printf("Yes\n");
            } 
            else printf("No\n");
            Reset(T);
        }
        Free(T);
        scanf("%d",&N);        
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43919570/article/details/105196699