其实如果不用 Stack 而改用 List 的话,三种非递归遍历将变得更加简单一致,一个 While 就够了
typedef std::list<BinaryTree::PTreeNode> TreeNodeList;
typedef struct TreeNode
{
Item Node;
TreeNode* pRight;
TreeNode* pLeft;
bool bVisited; // 关键
TreeNode(Item node = 0, TreeNode* pright = NULL, TreeNode* pleft = NULL)
: Node(node)
, pRight(pright)
, pLeft(pleft)
, bVisited(false)
{
}
}TreeNode, *PTreeNode;
// 非递归前序遍历树
void BinaryTree::NoRecPreTraverseImpl(PTreeNode pTreenode)
{
if (NULL == pTreenode)
return;
TreeNodeList NodeList;
PTreeNode pNode;
NodeList.push_front(pTreenode);
while (!NodeList.empty())
{
pNode = NodeList.front();
NodeList.pop_front();
std::cout << "Item = " << pNode->Node << std::endl;
if(pNode->pRight != NULL) NodeList.push_front(pNode->pRight);
if(pNode->pLeft != NULL) NodeList.push_front(pNode->pLeft);
}
}
// 非递归中序遍历树
void BinaryTree::NoRecInTraverseImpl(PTreeNode pTreenode)
{
if (NULL == pTreenode)
return;
TreeNodeList NodeList;
PTreeNode pNode;
NodeList.push_front(pTreenode);
while (!NodeList.empty())
{
pNode = NodeList.front();
if(pNode->bVisited)
{
NodeList.pop_front();
pNode->bVisited = false; // 为下一次遍历做准备
std::cout << "Item = " << pNode->Node << std::endl;
if(pNode->pRight != NULL) NodeList.push_front(pNode->pRight);
}
else
{
if(pNode->pLeft != NULL) NodeList.push_front(pNode->pLeft);
pNode->bVisited = true;
}
}
}
// 非递归后序遍历树
void BinaryTree::NoRecPostTraverseImpl(PTreeNode pTreenode)
{
if (NULL == pTreenode)
return;
TreeNodeList NodeList;
PTreeNode pNode;
NodeList.push_front(pTreenode);
while (!NodeList.empty())
{
pNode = NodeList.front();
if(pNode->bVisited)
{
NodeList.pop_front();
pNode->bVisited = false; // 为下一次遍历做准备
std::cout << "Item = " << pNode->Node << std::endl;
}
else
{
if(pNode->pRight != NULL) NodeList.push_front(pNode->pRight);
if(pNode->pLeft != NULL) NodeList.push_front(pNode->pLeft);
pNode->bVisited = true;
}
}
}
回复 更多评论