📜  一次遍历中二叉树的前序、后序和按序遍历 | (使用递归)

📅  最后修改于: 2022-05-13 01:56:09.136000             🧑  作者: Mango

一次遍历中二叉树的前序、后序和按序遍历 | (使用递归)

给定一棵二叉树,任务是在一次迭代中以 Pre-order、Post-order 和 In-order 打印二叉树的所有节点。

例子:

方法:本文提供了该问题的迭代解决方案。这里这种方法是基于递归概念的。

请按照以下步骤解决问题。

  • 创建 3 个数组来存储中序、前序和后序遍历。
  • 将当前节点推入前序数组,并调用左孩子的递归函数。
  • 现在将当前节点推入中序数组,并对右子树(右子树)进行递归调用。
  • 在退出当前递归之前访问后序数组中的当前节点数据。

下面是上述方法的实现。

C++
// C++ program for above approach
 
#include 
using namespace std;
 
// Structure of a tree node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
    Node(int val)
    {
        data = val;
        left = NULL;
        right = NULL;
    }
};
 
// Function for traversing tree using
// preorder postorder and inorder method
void PostPreInOrderInOneFlowRecursive(Node* root,
                                      vector& pre,
                                      vector& post,
                                      vector& in)
{
 
    // Return if root is NULL
    if (root == NULL)
        return;
 
    // Pushes the root data into the pre
    // order vector
    pre.push_back(root->data);
 
    // Recursively calls for the left node
    PostPreInOrderInOneFlowRecursive(
        root->left, pre, post, in);
 
    // Pushes node data into the inorder vector
    in.push_back(root->data);
 
    // Recursively calls for the right node
    PostPreInOrderInOneFlowRecursive(
        root->right, pre, post, in);
 
    // Pushes the node data into the Post Order
    // Vector
    post.push_back(root->data);
}
 
// Driver Code
int main()
{
    struct Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->right = new Node(7);
    root->left->left->left = new Node(8);
    root->left->left->left->right
        = new Node(12);
    root->left->right->left = new Node(9);
    root->right->right->left = new Node(10);
    root->right->right->right = new Node(11);
 
    // Declaring the vector function to store
    // in, post, pre order values
    vector pre, post, in;
 
    // Calling the function;
    PostPreInOrderInOneFlowRecursive(
        root, pre, post, in);
 
    // Print the values of Pre order, Post order
    // and In order
    cout << "Pre Order : ";
    for (auto i : pre) {
        cout << i << " ";
    }
 
    cout << endl;
    cout << "Post Order : ";
    for (auto i : post) {
        cout << i << " ";
    }
    cout << endl;
    cout << "In Order : ";
    for (auto i : in) {
        cout << i << " ";
    }
    return 0;
}


输出
Pre Order : 1 2 4 8 12 5 9 3 6 7 10 11 
Post Order : 12 8 4 9 5 2 6 10 11 7 3 1 
In Order : 8 12 4 2 9 5 1 6 3 10 7 11 

时间复杂度: O(N)
辅助空间: O(N)