使用 C++ 在没有递归的情况下打印从根到叶的路径的程序
在本教程中,我们将讨论一个程序,该程序打印从根节点到给定二叉树中所有叶节点的路径。
例如,假设我们有以下二叉树
在这个二叉树中,我们有 4 个叶节点。因此,我们可以从根节点到叶节点有 4 条路径。
要解决这个问题,我们将使用迭代方法。在对二叉树执行前序遍历时,我们可以将父指针存储在映射中。每当在遍历过程中遇到叶节点时,我们就可以使用父指针轻松打印其从根节点的路径。
示例
#include <bits/stdc++.h>> using namespace std; struct Node{ int data; struct Node *left, *right; }; //to create a new node Node* create_node(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } //printing the path from root to leaf void print_cpath(Node* curr, map<Node*, Node*> parent){ stack<Node*> nodes_stack; while (curr){ nodes_stack.push(curr); curr = parent[curr]; } while (!nodes_stack.empty()){ curr = nodes_stack.top(); nodes_stack.pop(); cout << curr->data << " "; } cout << endl; } //to perform pre order traversal void preorder_traversal(Node* root){ if (root == NULL) return; stack<Node*> nodeStack; nodeStack.push(root); map<Node*, Node*> parent; parent[root] = NULL; while (!nodeStack.empty()){ Node* current = nodeStack.top(); nodeStack.pop(); if (!(current->left) && !(current->right)) print_cpath(current, parent); if (current->right){ parent[current->right] = current; nodeStack.push(current->right); } if (current->left){ parent[current->left] = current; nodeStack.push(current->left); } } } int main(){ Node* root = create_node(101); root->left = create_node(82); root->right = create_node(23); root->left->left = create_node(34); root->left->right = create_node(55); root->right->left = create_node(29); preorder_traversal(root); return 0; }
输出
101 82 34 101 82 55 101 23 29
广告