二叉树中从根结点到叶子结点的所有路径(递归实现)

来源:互联网 发布:淘宝网卡洛琳号船模型 编辑:程序博客网 时间:2024/04/27 21:12
    假设我们要输出二叉树中所有从根节点到叶子节点的所有路径,我们采用前序遍历二叉树的思想,每遇到一个节点,我们把该节点存储在数组中,然后判断该节点是否为叶子节点,如果是叶子节点,我们输出从根节点到该叶子节点的路径,并且在数组相应位置置空。如果不是叶子节点,我们递归进入该节点的非空子节点中。
#include<iostream>#include<vector>#include<algorithm>#include<stack>using namespace std;//树节点结构struct BinaryTreeNode{BinaryTreeNode *left;BinaryTreeNode *right;char value;};//存储路径的数组vector<char> path(10, '@');//创建二叉树void createTree(BinaryTreeNode* &root){char val;cin >> val;if (val != '@'){root = new BinaryTreeNode;root->value = val;root->left = NULL;root->right = NULL;createTree(root->left);createTree(root->right);}}//递归实现输出从根节点到叶子结束的所有路径void printPath(BinaryTreeNode *root, int pos){if (root == NULL)return;path[pos] = root->value;if (root->left == NULL && root->right == NULL){auto it = path.begin();auto end = find(path.begin(), path.end(), '@');while (it != end){cout << *it++ << " ";}cout << endl;}else{if (root->left != NULL){printPath(root->left, pos + 1);}if (root->right != NULL){printPath(root->right, pos + 1);}}path[pos] = '@';}int main(void){BinaryTreeNode *root = NULL;createTree(root);printPath(root, 0);system("pause");return 0;}
//存储所有的路径vector<vector<char>> allPath;//某条路径vector<char> path;void findAllPath(BinaryTreeNode *root){if (root == NULL)return;if (root->left == NULL && root->right == NULL){path.push_back(root->value);allPath.push_back(path);}else{path.push_back(root->value);if (root->left)findAllPath(root->left);if (root->right)findAllPath(root->right);}path.pop_back();}

0 0
原创粉丝点击