三种方法中,递归最为简单,栈次之,循环最为麻烦。递归的深度如果太大则会导致栈溢出;栈的方式需要额外的辅助空间;循环编程最麻烦。
首先是递归:
//递归方法
void midPrint_r(TreeNode* root)
{//中序遍历
if(root==NULL)
return;
if(root->left)
midPrint_r(root->left);
cout<<root->val<<" ";
if(root->right)
midPrint_r(root->right);
}
void prePrint_r(TreeNode* root)
{//前序遍历
if(root==NULL)
return;
cout<<root->val<<" ";
if(root->left)
prePrint_r(root->left);
if(root->right)
prePrint_r(root->right);
}
void postPrint_r(TreeNode* root)
{//中序遍历
if(root==NULL)
return;
if(root->left)
postPrint_r(root->left);
if(root->right)
postPrint_r(root->right);
cout<<root->val<<" ";
}
栈方法:先循环把结点压入到栈中,然后再逐个弹出;
//循环堆栈方法
void midPrint_l(TreeNode* root)
{
stack<TreeNode*> s;
TreeNode *cur = root;
while(!s.empty() || cur != NULL)
{
while(cur != NULL)
{
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
cout<<cur->val<<" ";
cur = cur->right;
}
}
void prePrint_l(TreeNode* root)
{
stack<TreeNode*> s;
TreeNode *cur = root;
while(!s.empty() || cur != NULL)
{
while(cur != NU