构造的二叉树结构如下:
运行结果如下:
代码如下:
#include聽
#include聽
using聽namespace聽std;
typedef聽struct聽tnode聽//定义树节点结构
{
int聽val;
tnode*聽left;
tnode*聽right;
tnode(int聽x=0):val(x),left(NULL),right(NULL){}//默认构造函数
}TreeNode,*pTreeNode;
void聽getPath(TreeNode*聽cur,vector&resAllPath,vector聽path,vector&聽leafNode)//深度优先遍历dfs
{
聽
聽聽聽聽path.push_back(cur);
聽聽聽聽if(cur->left==NULL聽&&聽cur->right==NULL)
聽聽聽聽{
leafNode.push_back(cur);
聽聽聽聽聽聽聽聽resAllPath.push_back(path);
聽聽聽聽聽聽聽聽return;
聽聽聽聽}
聽聽聽聽if(cur->left)
聽聽聽聽{
聽聽聽聽聽聽聽聽getPath(cur->left,resAllPath,path,leafNode);
聽聽聽聽}
聽聽聽聽if(cur->right)
聽聽聽聽{
聽聽聽聽聽聽聽聽getPath(cur->right,resAllPath,path,leafNode);
聽聽聽聽}
聽聽聽聽聽聽聽聽
}
vector聽getLeafPathAndNode(TreeNode聽*root,vector&聽leafNode)聽//获取叶节点及其路径
{
聽聽聽聽聽
聽聽聽聽vector聽resAllPath;
聽聽聽聽vector聽path;
聽聽聽聽聽聽聽聽
聽聽聽聽if(root==NULL)
聽聽聽聽聽聽聽聽return聽resAllPath;
聽聽聽聽聽聽聽聽
聽聽聽聽getPath(root,resAllPath,path,leafNode);
聽聽聽聽return聽resAllPath;
聽聽聽聽聽聽
}
void聽printAllPath(vector&聽leafPath)//打印所有叶子节点路径
{
vector::iterator聽it1;
vector::iterator聽it2;
cout |