python中怎么分析循環(huán)遍歷二叉樹,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
超過10余年行業(yè)經(jīng)驗(yàn),技術(shù)領(lǐng)先,服務(wù)至上的經(jīng)營模式,全靠網(wǎng)絡(luò)和口碑獲得客戶,為自己降低成本,也就是為客戶降低成本。到目前業(yè)務(wù)范圍包括了:網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作,成都網(wǎng)站推廣,成都網(wǎng)站優(yōu)化,整體網(wǎng)絡(luò)托管,小程序開發(fā),微信開發(fā),App定制開發(fā),同時(shí)也可以讓客戶的網(wǎng)站和網(wǎng)絡(luò)營銷和我們一樣獲得訂單和生意!
前序遍歷
struct Node { Node*left; Node*right; int data; Node(){ func; } }; Node* create(Node*p, int depth) { if (p && depth) { p->left = new Node; p->right = new Node; p->data = depth; create(p->left, depth - 1); create(p->right, depth - 1); } if (!depth) { p->left = nullptr; p->right = nullptr; p->data = depth; } return p; } void print1(Node*p) { if (p) { cout << p->data << " "; print1(p->left); print1(p->right); } } void print2(Node*head)//利用stack 模擬函數(shù)調(diào)用過程 來遍歷{ stacks; Node*p = head; { while (p) { s.push(p); cout << p->data << " "; p = p->left; } while (!s.empty()) { Node*pp = s.top(); if (pp->right && pp != head) { cout << pp->right->data << " "; } s.pop(); } } { p = head->right; while (p) { s.push(p); cout << p->data << " "; p = p->left; } while (!s.empty()) { Node*pp = s.top(); if (pp->right && pp != head) { cout << pp->right->data << " "; } s.pop(); } } } int main() { Node* head = new Node; create(head, 2); head->data = 10; head->left->data = 6; head->right->data = 14; head->left->left->data = 4; head->left->right->data = 8; head->right->left->data = 12; head->right->right->data = 16; print1(head);//遞歸遍歷 cout << endl; print2(head);//循環(huán)遍歷 system("pause"); return 0; }
中序
void print2(Node*head) { stacks; Node*p = head; { while (p) { s.push(p); // cout << p->data << " "; p = p->left; } while (!s.empty()) { Node*pp = s.top(); cout << pp->data << " "; if (pp->right && pp != head ) { cout << pp->right->data << " "; } s.pop(); } } { p = head->right; while (p) { s.push(p); p = p->left; } while (!s.empty()) { Node*pp = s.top(); cout << pp->data << " "; if (pp->right&& pp != head) { cout << pp->right->data << " "; } s.pop(); } } }
后序
void print2(Node*head) { stacks; Node*p = head; { while (p) { s.push(p); p = p->left; } while (!s.empty()) { Node*pp = s.top(); if (pp->right && pp != head ) { cout << pp->right->data << " "; } if ( pp != head) cout << pp->data << " "; s.pop(); } } { p = head->right; while (p) { s.push(p); p = p->left; } while (!s.empty()) { Node*pp = s.top(); if (pp->right&& pp != head) { cout << pp->right->data << " "; } cout << pp->data << " "; s.pop(); } } cout << head->data << " "; }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。