数据结构——从叶子结点到根节点的全部路径
生活随笔
收集整理的這篇文章主要介紹了
数据结构——从叶子结点到根节点的全部路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題
給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-paths
257.二叉樹的所有路徑
與此問題類似的問題
數據結構——二叉樹的最長路徑問題
思路:
核心代碼
全部代碼(可以直接運行)
#include<stdio.h> #include<bits/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=='#')T=NULL;else {T=(BiNode*)malloc(sizeof(BiNode));if(!T)exit(-1);T->data=ch;CreateBiTree(T->lchild);CreateBiTree(T->rchild);} } void leaf_root(BiTree T,int *path,int len) {if(T){if(T->lchild==NULL&&T->rchild==NULL)//當T為葉子結點時,逆序輸出 {printf("%c->",T->data);for(int i=len-1;i>0;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 len=0;printf("輸出全部從葉子結點到根節點的路徑:\n"); leaf_root(T,path,len);}總結
以上是生活随笔為你收集整理的数据结构——从叶子结点到根节点的全部路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赵二狗在哪逆水寒野外溶洞赵二狗在哪里位置
- 下一篇: 数据结构——二叉树的递归算法