void preorder_print(TreeNode* leaf)
{
if(leaf == nullptr)
return;
std::stack<int> s;
TreeNode* tmp ;
s.clear(); //
s.push(leaf);
while(!s.empty())
{
tmp = s.pop();
cout << tmp->value << ', ' ;
if(leaf->right != nullptr)
s.push(leaf->right);
if(leaf->left != nullptr)
s.push(leaf->left);
}
}
void inorder_print(TreeNode* leaf)
{
std::stack<int> s ;
s.clear();
TreeNode *tmp;
while( !s.empty() || leaf!=nullptr)
{
if(leaf != nullptr)
{
s.push(leaf);
leaf = leaf->left;
}else
{
tmp = s.top();
s.pop();
cout << tmp->value << ', ' ;
leaf = leaf->right;
}
}
}
void postorder_print(TreeNode* leaf)
{
std::stack<int> s ;
s.clear();
TreeNode *lastNodeVisited = nullptr ;
TreeNode *peekNode = nullptr;
while( !s.empty() || leaf != nullptr)
{
if(leaf != nullptr)
{
s.push(leaf);
leaf = leaf->left;
}else
{
peekNode = s.top();
if(peekNode->right != nullptr && lastNodeVisited != peekNode->right)
leaf = peekNode->right;
else
{
cout << peekNode->value << ', ';
lastNodeVisited = s.top();
s.pop();
}
}
}
}
void bfs_print(TreeNode* leaf)
{
std::queue<int> q ;
q.clear();
q.push(leaf);
TreeNode *node;
while( ! q.empty())
{
node = q.front();
q.pop();
cout << node->vaue << ', ';
if(node->left != nullptr)
q.push(node->left);
if(node->right != nullptr)
q.push(node->right)
}
}
近期评论