0
我嘗試將所有根打印到二叉樹中的葉子路徑的代碼。將所有根打印到葉子路徑
#include<iostream>
#include<stack>
using namespace std;
bool visited[100];
void intilize(){
for(int i=0;i<100;i++)
visited[i]=false;
}
struct node
{
int data;
struct node *left,*right;
};
struct node* createNode(int k)
{
struct node* temp = new node;
temp->left = NULL;
temp->right = NULL;
temp->data = k;
return temp;
}
stack<node*> s,s1;
void print(){
while(!s.empty()){
s1.push(s.top());
s.pop();
}
while(!s1.empty()){
struct node* a= s1.top();
cout<<a->data<<" ";
s1.pop();
s.push(a);
if(s1.empty())
return;
}
}
void printpath(struct node* node){
if(node==NULL) return;
s.push(node);
while(!s.empty()){
struct node* top=s.top();
visited[top->data]=true;
if(top->left!=NULL&&visited[top->left->data]==false)
printpath(top->left);
else if(top->right!=NULL&&visited[top->right->data]==false)
printpath(top->right);
else if(top->left==NULL&&top->right==NULL){
print();
cout<<"\n";
}
s.pop();
}
}
int main() {
struct node* root = createNode(50);
root->left = createNode(7);
root->right = createNode(2);
root->right->left = createNode(1);
root->right->right = createNode(30);
root->right->right->right = createNode(40);
root->right->left->left = createNode(10);
root->right->left->left->left = createNode(12);
intilize();
printpath(root);
return 0;
}
該代碼給出了分段錯誤,因爲終止條件存在一些問題。 有人可以幫我解決問題。