日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据结构——从叶子结点到根节点的全部路径

發布時間:2023/12/4 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构——从叶子结点到根节点的全部路径 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題

給定一個二叉樹,返回所有從根節點到葉子節點的路徑。

說明: 葉子節點是指沒有子節點的節點。

示例:

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-paths
257.二叉樹的所有路徑

與此問題類似的問題
數據結構——二叉樹的最長路徑問題

思路:

  • 遇到的是葉子結點,將當前結點輸出(也就不需要進入數組了),并將數組的元素逆序輸出。
  • 遇到的不是葉子結點,將該元素進入數組。遞歸實現左右子樹。
    核心代碼
  • 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);}} }

    全部代碼(可以直接運行)

    #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);}

    總結

    以上是生活随笔為你收集整理的数据结构——从叶子结点到根节点的全部路径的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。