二叉树非递归遍历
介绍二叉树的非递归算法(利用栈和父节点),实现相比较来说较为简单,代码更加简洁,逻辑清晰
一、先序遍历
<1>栈模拟实现
void PreorderTraversal(BinaryTree T) { stack S; while (T != nullptr || !S.empty()) { if (T != nullptr) { Visit(T); S.push(T); T = T->left; } else { T = S.pop(); T = T->right; } } }
<2>父节点实现
void PreOrderTransval(BinaryTree T) { while (T != nullptr) { Visit(T); if (T->left != nullptr) T = T->left; else if (T->right != nullptr) T = T->right; else { BinaryTree child; while (1) { child = T; T = T->parent; if (T == nullptr) break; if (T->right != nullptr && T->left == child) { T = T->right; break; } } } } }
二、中序遍历
<1>栈模拟实现
void InorderTraversal(BinaryTree T) { stack S; while (T != nullptr || !S.empty()) { if (T != nullptr) { S.push(T); T = T->left; } else { T = S.pop( ); Visit(T); T = T->right; } } }
<2>父节点实现
void InorderTraversal(BinaryTree T) { int mark = 0; while (T != nullptr) { if (mark == 0) { if (T->left != nullptr) T = T->left; else mark = 1; } else { BinaryTree child; Visit(T); if (T->right != nullptr) { T = T->right; mark = 1; } else { while(1) { child = T; T = T->parent; if (T == nullptr) break; if (T->left == child) { mark = 1; break; } } } } } }
三、后序遍历
<1>栈模拟
typedef struct { BinaryTree node = nullptr; int mark = 0; }Node; void PostOrder(BinaryTree bt) { stack<Node> s; Node tmpCell; while (bt || !s.empty()) { if (bt) { tmpCell.node = bt; tmpCell.mark = 0; s.push(tmpCell); bt = bt->left; } else { tmpCell = s.top( ); s.pop( ); if (tmpCell.mark == 0) { tmpCell.mark = 1; s.push(tmpCell); bt = bt->right; } else { Visit(tmpCell.node); bt = nullptr; } } } }