Почему при печати обхода предзаказа BST моя программа ничего не делает - PullRequest
0 голосов
/ 15 января 2012

Я пытаюсь создать код, который позволяет мне войти в узел дерева и затем указать его обход по предзаказу, но не понимаю, что происходит. Что я делаю не так?

Это мой код:

#include <stdio.h>
#include<iostream>
#include<queue>
#define MAX 100
#include <vector>
#include <stdlib.h>

typedef struct node {
    struct node *parent;
    struct node *left;
    struct node *right;

    int value;
} Node;

typedef struct tree {
    Node *root;
} Tree;

void findPlace(Node *_toAdd, Node *_current) {
    // set this node to the parent so we dont have to do it later (may change next recursion)
    _toAdd->parent = _current;

    // compare value of node we're adding to current node
    if(_toAdd->value < _current->value)
        // add the element to the left subtree
        if(_current->left == NULL)          // if no left subtree yet, add it right here
            _current->left = _toAdd;
        else                                        // otherwise continue recursion to left subtree
            findPlace(_toAdd, _current->left);
    else
        // add the element to the right subtree
        if(_current->right == NULL)     // if no right subtree yet, add it right here
            _current->right = _toAdd;
        else                                        // otherwise, continue recursing to the right subtree
            findPlace(_toAdd, _current->right);
}

Node *addNode(int _val, Tree* _tree) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->value = _val;

    // if the tree is empty, this is the new root
    if(_tree->root == NULL)
        _tree->root = newNode;

    // otherwise, we need to find the right place to put it
    else
        findPlace(newNode, _tree->root);

    // return reference to the node
    return newNode;
}


void preOrder(Node *);


int main() {
    // create a tree to fool around with
    Tree *myTree = (Tree *)malloc(sizeof(Tree));

    // Add some values to the tree
    addNode(7, myTree);
    addNode(3, myTree);
    addNode(7, myTree);
    addNode(11, myTree);
    addNode(6, myTree);
    addNode(8, myTree);
    addNode(12, myTree);
    addNode(0, myTree);
    addNode(2, myTree);
    addNode(9, myTree);

    printf("Pre-Order Traversal: "); preOrder(myTree->root); printf("\n");



    return 0;
}

void preOrder(Node *_root)
{
    printf("%d ", _root->value);
    if(_root->left != NULL)
        preOrder(_root->left);
    if(_root->right != NULL)
        preOrder(_root->right);
}

Предполагается, что вызывая действие preorder, оно должно напечатать дерево в таком порядке, но программа просто завершает работу и ничего не печатает, я застрял с этим, пожалуйста, помогите мне, и извините мой английский

1 Ответ

1 голос
/ 15 января 2012

Я думаю, что ваша проблема в том, что у вас ничего не останавливается при выходе из программы ... просто используйте cin

int x;
cin >> x;

return 0;
...