Java教程

建二叉树

本文主要是介绍建二叉树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#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输入结束。

这篇关于建二叉树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!