【发布时间】:2014-02-17 17:05:07
【问题描述】:
我正在尝试编写一个代码来移除树的叶子并打印树的其余部分。
在平衡树的情况下,我能够获得正确的输出。例如
1
/ \
2 3
/ \ \
4 5 6
这棵树的输出必须是213(按顺序打印时)
当它是一棵不平衡的树时,我无法获得所需的输出。例如
1
/ \
2 3
/ \ \
4 5 6
/ \
7 8
我收到4 3 2 5 1 3. which is wrong.
correct answer is 4 2 1 3.(printed inorder)
谁能帮我看看我犯了什么错误?
程序的代码是
//prune a tree
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node *left;
struct Node *right;
};
struct Node *follower=NULL;
struct Node *create_node(int item)
{
struct Node *newNode=NULL;
newNode= new Node;
newNode->data=item;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
void extract_leaves_binary_tree(struct Node *root)
{
int na=0;
if(root==NULL)
return;
if(root->left==NULL && root->right==NULL)
{
na=1;
}
else
{
follower=root;
}
if(na==1 )
{
if(follower->left==root)
follower->left=NULL;
if(follower->right==root)
follower->right=NULL;
na=0;
}
extract_leaves_binary_tree(root->left);
extract_leaves_binary_tree(root->right);
}
void print(struct Node *root)
{
if(root==NULL)
return;
print(root->left);
cout<<root->data;
print(root->right);
}
void driver(struct Node *root)
{
extract_leaves_binary_tree(root);
}
int main()
{
struct Node *root=NULL;
root = create_node(1);
root->left = create_node(2);
root->right = create_node(3);
root->left->left = create_node(4);
root->left->right = create_node(5);
root->right->right = create_node(6);
root->left->left->left = create_node(7);
root->left->left->right = create_node(8);
driver(root);
cout<<"inordrer"<<endl;
print(root);
return 0;
}
【问题讨论】:
-
没有称为“C/C++”的语言。您的代码显然是 C++。从标题中删除了“c/c++”并删除了 C 标记。
-
@slim - 这个方法就在那里。他正在删除所有的叶子节点。
-
您正在使用全局变量。这是你的问题。做。不是。采用。全局变量。
-
我尝试在里面声明它。我遇到分段错误。
-
这不是使用全局的借口。没有什么是。再试一次。