正在打印所有根到叶路径
Printing all root to leaf paths
我试图在二进制树中打印所有根到叶路径的代码。
#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;
}
该代码给出分段错误,因为终止条件存在一些问题。有人能帮我解决这个问题吗。
这种方法过于复杂和脆弱。
不需要单独的堆栈。
不需要单独的"可见"数组。
所需要的只是一个股票递归访问者,它递归地下降到这个树中,它还为堆栈上动态构建的结构添加了一个额外的参数,该结构使用类似于的链接列表动态构建到根的路径
struct path_to_root {
struct path_to_root *next;
struct node *n;
};
现在,打印每个叶子注释的路径所需要的只是一个沼泽标准访问者,它在树上递归迭代,以及这个额外的参数。以下是一般方法的大致想法:
void printpath(struct node *n, struct path_to_root *p)
{
struct path_to_root pnext;
if (!n)
return;
if (!n->left && !n->right)
{
/* Your homework assignment here is to print the path that's in "p" */
}
pnext.n=n;
pnext.next=p;
printpath(n->left, &pnext);
printpath(n->right, &pnext);
}
这将被调用为:
printpath(root, NULL);
如前所述,您的家庭作业是在指定的空间中使用p
参数来实现打印叶的路径的实际代码。此时,叶的路径将在p
参数中找到。
现在,这里有一个棘手的部分是,p
将是叶的父级,p->next
将是它的祖父母,等等。所以路径是从下到上的,而不是从上到下的,但这是一个小细节,可以在打印代码中处理。
或者,以同样的方式从上到下动态构建到叶子的路径也不会有太多额外的工作。
相关文章:
- 如何将更多文件夹添加到c++include路径
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- C++A*算法并不总是在路径中具有目标节点
- 从函数角度看ID到文件路径的内部与外部映射
- boost xml parsingl将xml的路径作为变量发送
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- 如何使用cppcheck处理半相对包含路径
- 在C++中设置基于操作系统的文件路径
- 基于编译器选项的编译二进制路径
- 按边长度递归搜索图中所有可行路径
- 使用变量值作为 PlaySound 中的路径
- 如何转换真实路径 CString c++
- 从 GUID 获取 USB 卷路径
- 查找 GCD:并非所有控制路径都返回值
- C++17 文件系统::remove_all 带有通配符路径
- 在带有尾部斜杠的路径上返回 std::filesystem::create_directories() 的值
- 获取当前正在运行的 exe 名称(不是路径)
- 具有最大不同节点的根到叶路径
- 列出并计算二叉树从根结点到叶结点的权重最大的路径
- 正在打印所有根到叶路径