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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

数据结构——二叉树的最长路径问题

發(fā)布時間:2023/12/4 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构——二叉树的最长路径问题 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

題目:

求任意二叉樹中第一條最長的路徑長度,并輸出此路徑上各結點的值。
描述
設二叉樹中每個結點的元素均為一個字符,按先序遍歷的順序建立二叉鏈表,編寫算法求出該二叉樹中第一條最長的路徑。

輸入
一行數據,為二叉樹的先序序列(序列中元素為‘#’時,表示該結點為空)。
輸出
第一行為二叉樹的最長路徑長度,第二行為此路徑上從根到葉結點的各結點的值。
思路:(遞歸)

  • 函數longest_path(BiTree T,int *path,int &len,int *longestpath,int &longest_len)
    //char path[] 每次循環(huán)得到的路徑
    //char longestpath[]最長路徑
    //int &longest_len最長路徑的大小
    //int &len每次循環(huán)得到的路徑的大小
  • 代碼運行時:遇到的不是葉子結點,該條路徑繼續(xù)
    path[len++]T->data;再遞歸調用該函數,這個節(jié)點的左子樹,右子樹;
  • 遇到的時葉子結點時,該條路徑結束,與之前的最長路徑比較,更新最長路徑(可能會);
  • 求最長路徑算法(核心代碼)

    void longest_path(BiTree T,int *path,int &len,int *longestpath,int &longest_len) {if(T!=NULL){if(T->lchild==NULL&&T->rchild==NULL)//當遇到葉子結點時,該條路徑完畢 {path[len]=T->data;if(len>longest_len)//如果長于longest_len就替換 {for(int j=0;j<=len;j++){longestpath[j]=path[j];}longest_len=len;//longest_len更新 }}else//當遇到的不是葉子結點時,該條路徑繼續(xù) {path[len++]=T->data;longest_path(T->lchild ,path,len,longestpath,longest_len);longest_path(T->rchild ,path,len,longestpath,longest_len);len--;}} }

    全部可執(zhí)行代碼

    #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)//二叉樹的先序創(chuàng)建 {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 longest_path(BiTree T,int *path,int &len,int *longestpath,int &longest_len) {if(T!=NULL){if(T->lchild==NULL&&T->rchild==NULL)//當遇到葉子結點時,該條路徑完畢 {path[len]=T->data;if(len>longest_len)//如果長于longest_len就替換 {for(int j=0;j<=len;j++){longestpath[j]=path[j];}longest_len=len;//longest_len更新 }}else//當遇到的不是葉子結點時,該條路徑繼續(xù) {path[len++]=T->data;longest_path(T->lchild ,path,len,longestpath,longest_len);longest_path(T->rchild ,path,len,longestpath,longest_len);len--;}} } int main() {BiTree T;printf("創(chuàng)建樹輸入樹T的先序序列(其中使用#代表空節(jié)點)\n");CreateBiTree(T);int path[MAX]={0};int longestpath[MAX]={0};int len=0;int longest_len=0;longest_path(T,path,len,longestpath,longest_len);printf("第一條最長的路徑長度為:%d\n",longest_len);printf("路徑為:"); for(int i=0;i<=longest_len;i++){printf("%c ->",longestpath[i]);}printf("NULL");}

    總結

    以上是生活随笔為你收集整理的数据结构——二叉树的最长路径问题的全部內容,希望文章能夠幫你解決所遇到的問題。

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