数据结构——二叉树的最长路径问题
生活随笔
收集整理的這篇文章主要介紹了
数据结构——二叉树的最长路径问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
求任意二叉樹中第一條最長的路徑長度,并輸出此路徑上各結點的值。
描述
設二叉樹中每個結點的元素均為一個字符,按先序遍歷的順序建立二叉鏈表,編寫算法求出該二叉樹中第一條最長的路徑。
輸入
一行數據,為二叉樹的先序序列(序列中元素為‘#’時,表示該結點為空)。
輸出
第一行為二叉樹的最長路徑長度,第二行為此路徑上從根到葉結點的各結點的值。
思路:(遞歸)
//char path[] 每次循環得到的路徑
//char longestpath[]最長路徑
//int &longest_len最長路徑的大小
//int &len每次循環得到的路徑的大小
path[len++]T->data;再遞歸調用該函數,這個節點的左子樹,右子樹;
求最長路徑算法(核心代碼)
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//當遇到的不是葉子結點時,該條路徑繼續 {path[len++]=T->data;longest_path(T->lchild ,path,len,longestpath,longest_len);longest_path(T->rchild ,path,len,longestpath,longest_len);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 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//當遇到的不是葉子結點時,該條路徑繼續 {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("創建樹輸入樹T的先序序列(其中使用#代表空節點)\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");}總結
以上是生活随笔為你收集整理的数据结构——二叉树的最长路径问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 13999 元,三星 Galaxy Z
- 下一篇: 赵二狗在哪逆水寒野外溶洞赵二狗在哪里位置