In this paper, recursive method and the container with STL template are used to realize the longest node traversal.
The implementation code is as follows:
1#include <iostream>2#include <vector>3 4 using namespacestd;5 6typedefstructnode7 {8 CharData//node Data9 structNode *lchild,*rchild;//two fork tree node typesTen}bstree;//two fork tree node types One Avector<Char>path; - - voidCreateb (Bstree **p)//build a two-fork tree the { - Charch; -Cin>>ch; - if(ch!='.') + { -*p= (bstree*)malloc(sizeof(Bstree));//Application Space +(*p)->data=ch;//Spatial Assignment ACreateb (& (*p)->lchild);//creating a left sub-tree atCreateb (& (*p)->rchild);//Create right subtree - } - Else*p=null;//empty junction. - } - - intTreedepth (Bstree *root)//the depth of the tree in { - if(root==NULL) to return 0; + intLeft=treedepth (root->lchild); - intRight=treedepth (root->rchild); the return(left>right)? (left+1): (right+1); * } $ Panax Notoginseng voidFindlongestpath (Bstree *root)//find the first longest path - { thePath.push_back (root->data); + if(root->lchild==null&&root->lchild==NULL) A return; the if(Treedepth (Root->lchild) >=treedepth (root->rchild))//If the Zuozi height is greater than or right sub-tree height +Findlongestpath (Root->lchild);//Traverse Zuozi continue to find - ElseFindlongestpath (Root->rchild);//Traverse right subtree to find $ } $ - voidPrintpath () - { thevector<Char>:: iterator ite; - for(Ite=path.begin (); Ite!=path.end (); + +ite)Wuyicout<<*ite<<" "; thecout<<Endl; -Path.clear ();//Cleaning Containers Wu } - About voidMain () $ { -Bstree *root;//two fork root knot point -cout<<"Create Bstree Root:"<<endl;//create a two-fork tree -Createb (&root); Acout<<"Root ' s depth is"<<treedepth (Root) <<endl;//two fork Tree depth +Findlongestpath (root);//find the longest path thecout<<"The longest path is:"<<Endl; -Printpath ();//Print $}
The first longest path in the binary tree and outputs the values of the nodes on this path