0
点赞
收藏
分享

微信扫一扫

找出二叉树的根到所有叶子的路径


思路比较简单:主要的想法就是得到所有子树的路径,然后和根组合在一起。

如果是根节点,就root->val加入vector并返回.
如果不是根结点,那就对左右子树递归,得到以他们为根的路径。

vector<string> Print_Path(Node *root)//找出二叉树的根到所有叶子的路径
{
vector<string> re, leftPath, rightPath;
string path;
if (root == NULL)
return re;
path = to_string(root->data);
if (root->left == NULL && root->right == NULL){
re.push_back(path);
return re;
}
if (root->left != NULL)
leftPath = Print_Path(root->left);
if (root->right != NULL)
rightPath = Print_Path(root->right);
for (auto le : leftPath) {
string temp = path + "->" + le;
re.push_back(temp);
}
for (auto ri : rightPath) {
string temp = path + "->" + ri;
re.push_back(temp);
}

return re;
}

在main()函数中调用并输出

vector<string> P = Print_Path(t.root);
vector<string>::iterator iter = P.begin();//正向迭代器
for (; iter != P.end(); iter++) {//*iter = 100 可以用指针 对 迭代器 进行修改操作
cout << *iter << endl;
}

运行结果如下:

找出二叉树的根到所有叶子的路径_结点


举报

相关推荐

0 条评论