c++輸出二叉樹葉子結點並輸出葉子結點到根結點的路徑長度
阿新 • • 發佈:2019-01-01
#include<iostream> #include <string> using namespace std; //結構體 typedef struct node { char data; struct node *lchild,*rchild; }binary_tree,*tree; //構造一棵樹,以字元0作為空 void creat_tree(tree &t) { char ch; cin>>ch; if(ch == '0') { t=NULL; } else { t = new binary_tree; if(!t) exit(0); //如果沒成功申請空間 則退出 t->data=ch; creat_tree(t->lchild); creat_tree(t->rchild); } } //列印路徑 bool printPath(tree &t, char data) { if (t == NULL) return false; if (t->data == data || printPath(t->lchild,data) || printPath(t->rchild,data)) { cout<<t->data; //路徑上的結點標識打印出來 return true; } return false; } //輸出路徑長度 void printLeavesDepth(tree &t, size_t depth = 0) { if (t == NULL) return; if (t->lchild == NULL && t->rchild == NULL) { cout<<t->data<<": "<<depth<<endl; } else { printLeavesDepth(t->lchild, depth+1); printLeavesDepth(t->rchild, depth+1); } } //輸出葉子結點值 void DispLeaf(tree &t) { if(t) { if(t->lchild==NULL&&t->rchild==NULL) { cout<<t->data<<" "; } DispLeaf(t->lchild); DispLeaf(t->rchild); } } int main() { tree t; cout<<"請輸入二叉樹節點:(例如輸入:ab00c00)"; creat_tree(t); cout<<"輸出葉子結點"<<endl; DispLeaf(t); cout<<endl; cout<<"各個葉子結點到根結點的路徑長度"<<endl; printLeavesDepth(t,0); system("pause"); return 0; }