二叉树的三种递归方法:前序、中序和后序。
前序遍历:先根节点,再左孩子,最后右孩子。
递归实现:
//前序递归
void PreorderRecusively(BinaryTree *root){
if(root == NULL)
return;
cout<<root->val<<endl;
PreorderRecusively(root->lchild);
PreorderRecusively(root->rchild);
}
非递归实现:
//前序非递归
void PreorderNoRecusively(BinaryTree *root){
if(root == NULL)
return;
stack<BinaryTree*> s;
BinaryTree *p = root;
s.push(p);
while(!s.empty())
{
p = s.top();
s.pop();
cout<<p->val<<endl;
if(p->rchild != NULL)
s.push(p->rchild);
if(p->lchild != NULL)
s.push(p->lchild);
}
}
中序遍历:先左孩子,再根节点,最后右孩子
递归实现:
//中序递归
void InorderRecusively(BinaryTree *root){
if(root == NULL)
return;
InorderRecusively(root->lchild);
cout<<root->val<<endl;
InorderRecusively(root->rchild);
}
非递归实现:
//中序非递归
void InorderNoRecusively(BinaryTree *root){
if(root == NULL)
return;
BinaryTree *p = root;
stack<BinaryTree*> s;
while(p != NULL || !s.empty())
{
if(p != NULL){
s.push(p);
p = p->lchild;
}else{
p = s.top();
s.pop();
cout<<p->val<<endl;
p = p->rchild;
}
}
}
递归实现:
//后序递归
void PostRecusively(BinaryTree *root){
if(root == NULL)
return;
PostRecusively(root->lchild);
PostRecusively(root->rchild);
cout<<root->val<<endl;
}
非递归实现:
//后序非递归
void PostNoRecusively(BinaryTree *root){
if(root == NULL)
return;
BinaryTree *p = root, last =NULL;
stack<BinaryTree*> s;
while(p != NULL)
{
s.push(p);
p = p->lchild;
}
while(!s.empty())
{
p = s.top();
s.pop();
if(p->rchild == NULL || p->rchild == last)
{
cout<<p->val<<endl;
last == p;
}else{
s.push(p);
p = p->rchild;
while(p != NULL)
{
s.push(p);
p = p->lchild;
}
}
}
}