簡體   English   中英

c++ 問題以遞歸方式打印二叉樹

[英]c++ problem inorder printing binary tree recursively

我一直在練習一些舊的 C++ 問題以准備一些工作面試,我目前正在嘗試從數組遞歸構造二叉樹,然后遞歸地按順序打印它。 但是,在嘗試 output 結果時,我得到了一些奇怪的值。

問題:從數組[4,2,5,1,3]構造二叉樹,然后創建一個打印的function
它們遞歸地排序。

答:我可以打印結果,但是我的解決方案包含一些意外的 0,這些 0 也會打印在結果中。 我不知道那些 0 最終會如何出現在打印結果中..

這是我目前擁有的打印結果(注意值之間不需要的 0):
0 1 0 2 0 3 0 4 0 5 0

這是我寫的c++解決方案。 (只需復制並粘貼並在您的編譯器上運行它):

#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);
}

我想我對 c++ 和遞歸有點生疏了..希望你們能幫助我.thx

問題出在construct_tree 中。 對它的調用是:

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)

問題是,每次對construct_tree 的調用都會創建一個添加到樹中的新節點,即使num超出范圍也是如此。

泰德是對的。 嘗試按如下方式更改construct_tree:-
node *tmp = null;
if(num < SIZE)
{
tmp= new node();
......
}
return tmp;

你還有一個問題。 您對樹排序的算法高度依賴於您訪問數據的順序。 嘗試您的解決方案

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM