【发布时间】:2011-05-05 06:09:14
【问题描述】:
我一直在练习一些旧的 C++ 问题以准备一些工作面试,我目前正在尝试从数组中递归地构造一棵二叉树,然后也递归地按顺序打印它。但是,在尝试输出结果时,我得到了一些奇怪的值。
问题:从数组[4,2,5,1,3]构造二叉树,然后创建一个打印函数
它们递归地排序。
答案:我可以打印结果,但是我的解决方案包含一些意外的 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
【问题讨论】:
标签: c++ recursion tree binary-tree