二叉树中第一条最长的路径并输出此路径上各结点的值

本文采用递归方法和配合STL模板的容器实现最长结点的遍历。

实现代码如下:

 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6 typedef struct node
 7 {
 8 char data;//结点数据
 9 struct node *lchild,*rchild;//二叉树结点类型
10 }BSTree;//二叉树结点类型
11 
12 vector<char> path;
13 
14 void Createb(BSTree **p)//建立二叉树
15 {
16     char ch;
17     cin>>ch;
18     if(ch!='.')
19     {
20         *p=(BSTree*)malloc(sizeof(BSTree));//申请空间
21         (*p)->data=ch;//空间赋值
22         Createb(&(*p)->lchild);//生成左子树
23         Createb(&(*p)->rchild);//生成右子树
24     }
25     else *p=NULL;//空结点
26 }
27 
28 int TreeDepth(BSTree *root)//树的深度
29 {
30     if(root==NULL)
31         return 0;
32     int left=TreeDepth(root->lchild);
33     int right=TreeDepth(root->rchild);
34     return (left>right) ? (left+1) : (right+1);
35 }
36 
37 void Findlongestpath(BSTree *root)//找到第一条最长路径
38 {
39     path.push_back(root->data);
40     if(root->lchild==NULL&&root->lchild==NULL)
41         return;
42     if(TreeDepth(root->lchild)>=TreeDepth(root->rchild))//如果左子树高度大于或右子树高度
43     Findlongestpath(root->lchild);//遍历左子树继续查找
44     else Findlongestpath(root->rchild);//遍历右子树进行查找
45 }
46 
47 void printpath()
48 {
49     vector<char>::iterator ite;
50     for(ite=path.begin();ite!=path.end();++ite)
51         cout<<*ite<<" ";
52         cout<<endl;
53         path.clear();//清理容器
54 }
55         
56 void main()
57 {
58     BSTree *root;//二叉树根结点
59     cout<<"create BSTree root:"<<endl;//创建二叉树
60     Createb(&root);
61     cout<<"root's depth is"<<TreeDepth(root)<<endl;//二叉树深度
62     Findlongestpath(root);//找到最长路径
63     cout<<"the longest path is:"<<endl;
64     printpath();//打印
65 }

 

posted on 2016-05-08 21:56  wxdjss  阅读(1559)  评论(0编辑  收藏  举报

导航