树的四种遍历方法递归实现

中序遍历

void inOrder(node* root){
    if(root){    
        inOrder(root->l);
        printf("%d ",root->val);
        inOrder(root->r);
    }
}

前序遍历

void preOrder(node* root){
    if(root){    
        printf("%d ",root->val);
        preOrder(root->l);
        preOrder(root->r);
    }
}

后序遍历

void postOrder(node* root){
    if(root){    
        postOrder(root->l);
        postOrder(root->r);
        printf("%d ",root->val);
    }
}

层序遍历

void levelOrder(node* root){
    queue<node*> q;
    q.push(root);
    while(!q.empty()){
        node* temp=q.front();
        q.pop();
        printf("%d ",temp->val);
        if(temp->l)
            q.push(temp->l);
        if(temp->r)
            q.push(temp->r);        
    }
}

非递归遍历参考树的非递归遍历

原文地址:https://www.cnblogs.com/foodie-nils/p/13322063.html