如图所示二叉树:
对其分别进行前、中、后续遍历;
先序遍历:
(1)递归
void preorder(TreeNode* root)
{
if(root==NULL)
return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
(2)非递归(循环)利用栈的结构实现
void preorder(TreeNode* root)
{
std::stack<TreeNode*> s;
TreeNode* p=root;
while(p!=NULL||!s.empty())
{
while(p!=NULL)
{
cout<<p->data<<" ";
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top()->right;
s.pop();
}
}
}
中序遍历
(1)递归
void inorder(TreeNode* root)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
(2)非递归
void inorder(TreeNode* root)
{
TreeNode* p=root;
std::stack<TreeNode*> s;
while(p||!s.empty())
{
while(p)
{
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top();
cout<<p->data<<" ";
p=s.top()->right;
s.pop();
}
}
}
后序遍历
(1)递归
void pastorder(TreeNode* root)
{
if(root==NULL)
return;
pastorder(root->left);
pastorde(root->right);
cout<<root->data<<" ";
}
(2)非递归
void pastorder(Node *node)
{
Node *cur=node;
Node *pre=NULL;
stack<Node*> s;
s.push(cur);
while(!s.empty())
{
cur=s.top();
if((!cur->left&&!cur->right)||(pre&&(pre==cur->left||pre==cur->right)))
{
cout<<cur->data<<"";
pre=cur;
s.pop();
}
else
{
if(cur->right)
s.push(cur->right); //先入栈右结点,再入栈左结点,这样才能保证左结点先出站。
if(cur->left)
s.push(cur->left);
}
}
}