浙大陈越数据结构04-树4 是否同一棵二叉搜索树

本方法使用慕课上何老师讲的方法,使用C++实现

#include 
#include 

using namespace std;

struct TreeNode;
typedef TreeNode* treePointer;

struct TreeNode{
    int val;
    treePointer left;
    treePointer right;
    int flag;
    TreeNode(int num) : val(num), left(nullptr), right(nullptr), flag(0){}
};

treePointer buildTree(int N);
bool check(treePointer root, int N);
void freeTree(treePointer root);
treePointer insertNode(treePointer root, int val);
void reset(treePointer root);
bool inCheck(treePointer root, int val);

int main(){
    int N;
    cin >> N;
    while(N){
        int L;
        cin >> L;
        treePointer root = buildTree(N);
        for(int i = 0; i < L; i++){
            if(check(root, N))
                cout<< "Yes\n";
            else
                cout<<"No\n";
            reset(root);
        }
        freeTree(root);
        cin >> N;
    }
    return 0;
}

treePointer buildTree(int N){
    int val;
    cin >> val;
    treePointer root = new TreeNode(val);
    for(int i = 1; i < N; i++){
        cin >> val;
        if(root->val < val)
            root->right = insertNode(root->right, val);
        else if(root->val > val)
            root->left = insertNode(root->left, val);
    }
    return root;
}

treePointer insertNode(treePointer root, int val){
    if(root == nullptr){
        root = new TreeNode(val);
        return root;
    }
    if(root->val > val)
        root->left = insertNode(root->left, val);
    else if(root->val < val)
        root->right = insertNode(root->right, val);
    return root;
}

bool check(treePointer root, int N){
    vector record(N, 0);
    for(int i = 0; i < N; i++){
        cin >> record[i];
    }
    if(root->val != record[0])
        return false;
    else
        root->flag = 1;
    for(int i = 1; i < N; i++){
        if(!inCheck(root, record[i]))
            return false;
    }
    return true;
}

bool inCheck(treePointer root, int val){
    if(root->flag){
        if(root->val > val){
            return inCheck(root->left, val);
        }
        else if(root->val < val){
            return inCheck(root->right, val);
        }
        else return false;
    }
    else{
        if(root->val == val){
            root->flag = 1;
            return true;
        }
        else
            return false;
    }
}

void reset(treePointer root){
    if(root == nullptr) return;
    root->flag = 0;
    reset(root->left);
    reset(root->right);
}

void freeTree(treePointer root){
    if(root == nullptr) return;
    freeTree(root->left);
    freeTree(root->right);
    delete root;
}

你可能感兴趣的:(c++,算法)