python中怎么分析循环遍历二叉树
python中怎么分析循环遍历二叉树,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
超过10余年行业经验,技术领先,服务至上的经营模式,全靠网络和口碑获得客户,为自己降低成本,也就是为客户降低成本。到目前业务范围包括了:网站设计、成都网站制作,成都网站推广,成都网站优化,整体网络托管,小程序开发,微信开发,App定制开发,同时也可以让客户的网站和网络营销和我们一样获得订单和生意!
前序遍历
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 模拟函数调用过程 来遍历{ 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);//循环遍历 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 << " "; }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。
文章名称:python中怎么分析循环遍历二叉树
文章起源:http://azwzsj.com/article/gedgcd.html