建二叉树


#include<iostream>
using namespace std;
struct node {
    int data;
    node* left;
    node* right;
};
 struct list {
    node* p;
    list* next;
};
node * createTree() {
    node* root=NULL;
    int temp;
    list* head = (list*)malloc(sizeof(list)),*tail;
    tail = head;
    node* nodeCur=NULL, * nodeTemp=NULL;

    list* listCur = NULL,*listTemp = NULL;
    while (cin >> temp) {
        if (root == NULL) {
            root = (node*)malloc(sizeof(node));
            root->left = NULL;
            root->right = NULL;
            root->data = temp;
            nodeCur = root;
            head->p = root;
            head->next = NULL;
            listCur = head;
        }
        else {
            nodeTemp = (node*)malloc(sizeof(node));
            nodeTemp->data = temp;
            nodeTemp->left = NULL;
            nodeTemp->right = NULL;
            listTemp = (list*)malloc(sizeof(list));
            listTemp->next = NULL;
            listTemp->p = nodeTemp;
            tail->next = listTemp;
            tail = listTemp;
            if (nodeCur->left == NULL) {
                nodeCur->left = nodeTemp;
            }
            else {
                nodeCur->right = nodeTemp;
                listCur = listCur->next;
                nodeCur = listCur->p;
            }
        }
    }
    return root;
    
}
void preOrder(node* root) {
    if (root == NULL)
        return;
    else {
        cout << root->data<<"  ";
        preOrder(root->left);
        preOrder(root->right);
    }
}
int main() {
    node* root= createTree();;
    
    preOrder(root);
}

建立二叉树前序打印一下,ctrl+z输入结束。

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/274416.html

(0)
上一篇 2022年7月14日
下一篇 2022年7月14日

相关推荐

发表回复

登录后才能评论