Summary code/* *file:print binary Tree Road between Leaf A and leaf b *date:2015/8/2 *author:jinya *assert A--B *tra Verse root, left, right; Left, Root, right; Left, right, root; *so left was always before right * the leaf node traversal on the Ieft side has precedence over the leaf node on the side * */#include <iostream>using namespace std; #include <vecto r>/* *use three pointer tree to memory parent * */typedef struct node{int data;struct node * lchild;struct node * RCH Ild;struct Node * parent; *pnode;class Tree{public:node * proot;vector <pNode> vectpnode;public:tree (); Tree (Pnode proot), void Create (), void Create (Pnode &root), void Create (Pnode &root, pnode parent); void Travel_ Leaf (); void Travel_leaf (Pnode root); int find (int num); void Print_tree_road ();}; Tree::tree () {proot = Null;//proot->parent = Null;//proot->lchild = Null;//proot->rchild = NULL;//pRoot-> data = 0;//vectpnode = NULL;} Tree::tree (Pnode proot) {this->proot = Proot;this->proot->parent = Null;this->proot->lchild = NULL;This->proot->rchild = Null;this->proot->data = 0;//vectpnode = NULL;} void Tree::create () {Create (proot);} void Tree::create (Pnode &root) {Create (root, NULL);} void Tree::create (Pnode &root, pnode parent) {int d = 0;cin >> d;if (d) {root = new Node (); root->data = d;root- >parent = Parent;root->lchild = Null;root->rchild = Null;create (root->lchild, root); Create (root-> Rchild, root);} Else{root = NULL;}} void Tree::travel_leaf () {travel_leaf (proot);} void Tree::travel_leaf (Pnode root) {if (root) {cout << root->data << "";/* If a leaf node joins vector*/if (!root-> Lchild &&!root->rchild) {Vectpnode.insert (Vectpnode.end (), root);} Travel_leaf (Root->lchild); Travel_leaf (Root->rchild);}} int tree::find (int num) {for (int i = 0; i < vectpnode.size (); ++i) {if (vectpnode[i]->data = = num) {return i;}} return-1;} void Tree::p rint_tree_road () {cout << "all leaf nodes:"; for (int j = 0; J < Vectpnode.size (); ++J) {cout << Vectpnode[j]->datA << "";} cout << Endl << "--------enter two integers (must be a leaf node):" << endl;int nleaf;cin >> nleaf;int nstart = Find (nleaf ), cin >> Nleaf;int nend = Find (Nleaf), if ( -1 = = Nstart) {nstart = 0;} if ( -1 = = nend) {nend = Vectpnode.size ();} for (int i = Nstart; I < vectpnode.size () && i <= nend; ++i) {//cout << vectpnode[i]->data << " ";p Node pcur = Vectpnode[i];while (pcur) {if (!pcur->parent) {cout << pcur->data;break;} cout << pcur->data << "<--";p cur = pcur->parent;} cout << Endl;} cout << Endl;} int main () {Tree tree;tree.create (); Tree.travel_leaf (); Tree.print_tree_road (); return 0;}
Test data:
1 2 4 5 0 0 6 11 0 0 8 0 0 0 3 9 0 0 011 8
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Print the path between the two leaf nodes of a binary tree