威海西郊建设集团网站,网站导航下拉菜单代码,计算机前端好找工作吗,百度推广开户问题
给定一个二叉树#xff0c;返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例: 来源#xff1a;力扣#xff08;LeetCode#xff09; 链接#xff1a;https://leetcode-cn.com/problems/binary-tree-paths 257.二叉树的所有路径
与…问题
给定一个二叉树返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例: 来源力扣LeetCode 链接https://leetcode-cn.com/problems/binary-tree-paths 257.二叉树的所有路径
与此问题类似的问题 数据结构——二叉树的最长路径问题
思路
遇到的是叶子结点将当前结点输出也就不需要进入数组了并将数组的元素逆序输出。遇到的不是叶子结点将该元素进入数组。递归实现左右子树。 核心代码
void leaf_root(BiTree T,int *path,int len)
{if(T){if(T-lchildNULLT-rchildNULL)//当T为叶子结点时逆序输出 {printf(%c-,T-data);for(int ilen-1;i0;i--){printf(%c-,path[i]);}printf(%c,path[0]);printf(\n); }else//当不为终端结点时该节点对应的值进入数组 {path[len]T-data;leaf_root(T-lchild,path,len);leaf_root(T-rchild,path,len);}} } 全部代码可以直接运行
#includestdio.h
#includebits/stdc.h
#define MAX 200
typedef char TElemType;
typedef int status;
typedef struct BiNode
{TElemType data;struct BiNode *lchild;struct BiNode *rchild;
}BiNode,*BiTree;
void CreateBiTree(BiTree T)//二叉树的先序创建
{TElemType ch;scanf(%c,ch);if(ch#)TNULL;else {T(BiNode*)malloc(sizeof(BiNode));if(!T)exit(-1);T-datach;CreateBiTree(T-lchild);CreateBiTree(T-rchild);}
}
void leaf_root(BiTree T,int *path,int len)
{if(T){if(T-lchildNULLT-rchildNULL)//当T为叶子结点时逆序输出 {printf(%c-,T-data);for(int ilen-1;i0;i--){printf(%c-,path[i]);}printf(%c,path[0]);printf(\n); }else//当不为终端结点时该节点对应的值进入数组 {path[len]T-data;leaf_root(T-lchild,path,len);leaf_root(T-rchild,path,len);}} }
int main()
{BiTree T;printf(创建树输入树T的先序序列(其中使用#代表空节点)\n);CreateBiTree(T);int path[MAX]{0};int len0;printf(输出全部从叶子结点到根节点的路径\n); leaf_root(T,path,len);}