二叉树的创建和前序遍历

2019-01-30  本文已影响0人  奋斗live
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#include<stdlib.h>
struct TreeNode{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};
void createTree(struct TreeNode **p);
bool is_bool(struct TreeNode *p,int val);
bool isUnivalTree(struct TreeNode *p);
void  createTree(struct TreeNode **root){
    char ch;
    ch = getchar();
    if(ch=='*'){
        (*root) = NULL;
    }else{
        (*root) = (struct TreeNode *)malloc(sizeof(struct TreeNode *));
        if((*root)==NULL){
            printf("failure");
            exit(-1);
        }else{
            (*root)->val = ch-'0';
            createTree(&((*root)->left));
            createTree(&((*root)->right));
        }
    }
}

int temp;
bool flag = true;
bool isUnivalTree(struct TreeNode* root) {
        if(root==NULL){
                return true;
        }
        //temp = root->val;
        bool res = is_bool(root,root->val);
        return res;
}

bool is_bool(struct TreeNode * root,int val){
       if(root==NULL){
        return true;
    }
    if(root->val!=val){
        return false;
    }
    return is_bool(root->left,val) && is_bool(root->right,val);
}

void print(struct TreeNode * root){
    if(root==NULL){
        return;
    }
    printf("%d",root->val);
    print(root->left);
    print(root->right);
}
int main(){
    struct TreeNode * root;
    createTree(&root);
    print(root);
    //bool res = isUnivalTree(root);
    //printf("%d\n",res);
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读