Open In App

Construct the full k-ary tree from its preorder traversal

Last Updated : 15 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an array that contains the preorder traversal of the full k-ary tree, the task is to construct the full k-ary tree and return its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children.

Examples: 

Input: pre[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4}, k = 3
Output: Postorder traversal of constructed full k-ary tree is: 7 3 8 2 9 10 4 5 6 1
Explanation:

Construct-the-full-k-ary-tree-from-its-preorder-traversal

Approach:

The idea is to construct a full k-ary tree from its preorder traversal using a queue-based level-wise approach. Each node is assigned up to k children before moving to the next level. The postorder traversal is then performed by recursively visiting all children first and printing the root at the end.

Below is the implementation of the above approach: 

C++
// C++ program to build full k-ary tree from
// its pre traversal and to print the
// postorder traversal of the tree.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    vector<Node*> children;
    
    Node(int val) {
        data = val;
    }
};

// Function to construct the k-ary tree from 
// pre traversal
Node* buildKaryTree(const vector<int>& pre, int k) {
                        
    int n = pre.size();                    
    if (n == 0) return nullptr;
    
    // Create the current root node
    int idx = 0;
    Node* root = new Node(pre[idx]);
    idx++;
    
    // Queue to track parent nodes
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty() && idx < n) {
        Node* parent = q.front();
        q.pop();
        
        // Assign up to k children
        for (int i = 0; i < k && idx < n; i++) {
            Node* child = new Node(pre[idx++]);
            parent->children.push_back(child);
            q.push(child);
        }
    }
    
    return root;
}

void postorder(Node* root) {
    if (root == nullptr) return;
    for (Node* child : root->children) {
        postorder(child);
    }
    cout << root->data << " ";
}

int main() {
    vector<int> pre = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4};
    int k = 3;  
    Node* root = buildKaryTree(pre, k);
    postorder(root);
    
    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node[] children;
    int childCount;

    public Node(int val, int k) {
        data = val;
        children = new Node[k];
        childCount = 0;
    }
}

class GfG {
    static Node buildKaryTree(int[] pre, int k) {
        if (pre.length == 0) return null;

        // Initialize the root node
        Node root = new Node(pre[0], k);

        // Queue to track parent nodes
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        int idx = 1; // Start from the second element

        while (!q.isEmpty() && idx < pre.length) {
            Node parent = q.poll();

            // Assign up to k children
            for (int i = 0; i < k && idx < pre.length; i++) {
                Node child = new Node(pre[idx++], k);
                parent.children[parent.childCount++] = child;
                q.add(child);
            }
        }
        return root;
    }

    static void postorder(Node root) {
        if (root == null) return;
        for (int i = 0; i < root.childCount; i++) {
            postorder(root.children[i]);
        }
        System.out.print(root.data + " ");
    }

    public static void main(String[] args) {
        int[] pre = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4};
        int k = 3;

        Node root = buildKaryTree(pre, k);
        postorder(root);
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.children = []

# Function to construct the k-ary tree from pre traversal
def build_kary_tree(pre, k):
    if not pre:
        return None

    # Initialize the root node
    root = Node(pre[0])

    # Queue to track parent nodes
    queue = [root]
    idx = 1  # Start from the second element

    while queue and idx < len(pre):
        parent = queue.pop(0)

        # Assign up to k children
        for _ in range(k):
            if idx < len(pre):
                child = Node(pre[idx])
                parent.children.append(child)
                queue.append(child)
                idx += 1
            else:
                break

    return root

def postorder(root):
    if root is None:
        return
    for child in root.children:
        postorder(child)
    print(root.data, end=" ")

if __name__ == "__main__":
    pre = [1, 2, 5, 6, 7, 3, 8, 9, 10, 4]
    k = 3
    root = build_kary_tree(pre, k)
    postorder(root)
    print()
C#
// C# program to build full k-ary tree from
// its pre traversal and to print the
// postorder traversal of the tree.
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public List<Node> children;

    public Node(int val) {
        data = val;
        children = new List<Node>();
    }
}

class GfG {
    // Function to construct the k-ary tree from pre traversal
    static Node BuildKaryTree(List<int> pre, int k) {
        if (pre.Count == 0) return null;

        // Initialize the root node
        Node root = new Node(pre[0]);

        // Queue to track parent nodes
        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(root);
        int idx = 1;

        while (queue.Count > 0 && idx < pre.Count) {
            Node parent = queue.Dequeue();

            // Assign up to k children
            for (int i = 0; i < k && idx < pre.Count; i++) {
                Node child = new Node(pre[idx++]);
                parent.children.Add(child);
                queue.Enqueue(child);
            }
        }

        return root;
    }

    static void Postorder(Node root) {
        if (root == null) return;
        foreach (var child in root.children) {
            Postorder(child);
        }
        Console.Write(root.data + " ");
    }

    static void Main(string[] args) {
        List<int> pre = new List<int> { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 };
        int k = 3;

        Node root = BuildKaryTree(pre, k);
        Postorder(root);
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to build full k-ary tree from
// its pre traversal and to print the
// postorder traversal of the tree.
class Node {
    constructor(data) {
        this.data = data;
        this.children = [];
    }
}

// Function to construct the k-ary tree from pre traversal
function buildKaryTree(pre, k) {
    if (pre.length === 0) return null;

    // Initialize the root node
    let root = new Node(pre[0]);

    // Queue to track parent nodes
    let queue = [root];
    let idx = 1;

    while (queue.length > 0 && idx < pre.length) {
        let parent = queue.shift();

        // Assign up to k children
        for (let i = 0; i < k && idx < pre.length; i++) {
            let child = new Node(pre[idx++]);
            parent.children.push(child);
            queue.push(child);
        }
    }

    return root;
}

function postorder(root) {
    if (!root) return;
    for (let child of root.children) {
        postorder(child);
    }
    process.stdout.write(root.data + " ");
}

// Driver Code
const pre = [1, 2, 5, 6, 7, 3, 8, 9, 10, 4];
const k = 3;

const root = buildKaryTree(pre, k);
postorder(root);
console.log();

Output
7 3 8 2 9 10 4 5 6 1 

Time Complexity: O(n), as each node is created and processed once during tree construction and traversal.
Space Complexity: O(n), due to storing the tree structure and the queue used in level-wise construction.


Similar Reads