二叉树的前序、中序、后序线索化及遍历
前序线索化:
创新互联企业建站,十余年网站建设经验,专注于网站建设技术,精于网页设计,有多年建站和网站代运营经验,设计师为客户打造网络企业风格,提供周到的建站售前咨询和贴心的售后服务。对于网站设计、做网站中不同领域进行深入了解和探索,创新互联在网站建设中充分了解客户行业的需求,以灵动的思维在网页中充分展现,通过对客户行业精准市场调研,为客户提供的解决方案。
void _PrevOrderThreading(Node *cur, Node *& prev) { if(cur == NULL) { return; } if(cur->_left == NULL) { cur->_leftTag == THREAD; cur->_left = prev; } if(prev && prev->_right == NULL) { prev->_rightTag = THREAD; prev->_right = cur; } prev = cur; _PrevOrderThreading(cur->_left, prev); _PrevOrderThreading(cur->right, prev); }
前序遍历:
void PrevOrderThd() { Node *cur = _root; while(cur) { while(cur->_leftTag == LINK) { cout << cur->_data << " "; cur = cur->_left; } cout << cur->_data << " "; cur = cur->right; // // while(cur->_rightTag == THREAD) // { // cur = cur->_right; // cout << cur->_data << " "; // } // if(cur->_leftTag == LINK) // { // cur = cur->_left; // } // else // { // cur = cur->_right; // } } }
中序线索化:
void _InOrderThreading(Node *cur, Node *& prev) { if(cur == NULL) { return; } _InOrderThreading(cur->_left, prev); //线索化 if(cur->_left == NULL) { cur->_leftTag = THREAD; cur->_left = prev; } if(prev && prev->_right == NULL) { prev->_rightTag = THREAD; prev->_right = cur; } prev = cur; _InOrderThreading(cur->_right, prev); }
中序遍历:
void InOrderThd() { Node *cur = _root; while(cur) { //找最左节点 while(cur->_leftTag == LINK) { cur = cur->_left; } cout << cur->_data << " "; //访问连续后继 while(cur->_rightTag == THREAD) { cur = cur->_right; cout << cur->_data << " "; } cur = cur->_right; } }
后序线索化:
void _PostOrderThreading(Node *root, Node *&prev) { if (root == NULL) { return; } _PostOrderThreading(root->_LChild, prev); _PostOrderThreading(root->_RChild, prev); if (root->_LChild == NULL) { root->_LTag = THREAD; root->_LChild = prev; } if (prev->_RChild == NULL) { prev->_RTag = THREAD; prev->_RChild = root; } prev = root; }
后序遍历:
采用三叉链 或写一个查找根节点的方法
分享名称:二叉树的前序、中序、后序线索化及遍历
文章链接:http://scjbc.cn/article/gijsso.html