简体   繁体   中英

c++ problem inorder printing binary tree recursively

I have been practicing some old C++ problems to prepare for a few job interviews, and I am currently trying to recursively construct a binary tree from an array, and then print it inorder recursively as well. However, I got some weird values when trying to output the result.

Problem: construct binary tree from array [4,2,5,1,3], and then create a function that prints
them inorder recursively.

Answer: I am able to print the result, however my solution contains some unexpected 0's that also gets printed within the result. I dont have a clue how those 0's can end up being in the printed results..

Here is the printed result I currently have (notice the unwanted 0's between values):
0 1 0 2 0 3 0 4 0 5 0

Here is the c++ solution I have written. (Just copy and paste and run it on your compiler):

#include <iostream>

using namespace std;

const int SIZE = 5;

struct node{
    node *leftBranch;
    node *rightBranch;
    int val;
};

int data[SIZE] = {4,2,5,1,3};
node* construct_tree(int);
void print_tree(node*);

node * construct_tree(int num){
    node *tmp = new node();
    if(num < SIZE){
        tmp->leftBranch = construct_tree(2*num + 1);
        tmp->val = data[num];
        tmp->rightBranch = construct_tree(2*num + 2);
    }
    return tmp;
}

int main(){
    node *tree = construct_tree(0);
    print_tree(tree);
    return 0;
}

void print_tree(node* tree){
    if(tree == NULL)
        return;
    print_tree(tree->leftBranch);
    cout<<tree->val<<" ";
    print_tree(tree->rightBranch);
}

I think I have been a little rusty with c++ and recursion..I hope you guys can help me.thx

The problem is in construct_tree. The calls to it are:

construct_tree(0) -- from main()
    construct_tree(1)
        construct_tree(3)
            construct_tree(7)
            construct_tree(8)
        construct_tree(4)
            construct_tree(9)
            construct_tree(10)
    construct_tree(2)
        construct_tree(5)
        construct_tree(6)

The problem is, every call to construct_tree creates a new node that is added to your tree, even when num is out of range.

Ted is right. Try changing construct_tree as follows:-
node *tmp = null;
if(num < SIZE)
{
tmp= new node();
......
}
return tmp;

You have another problem. Your algorithm for ordering the tree is highly dependent on the order in which you visit the data. Try your solution on

int data[SIZE] = {5, 4, 3, 2, 1};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM