The Wayback Machine - https://web.archive.org/web/20240927060113/https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/
Open In App

Serialize and Deserialize a Binary Tree

Last Updated : 20 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
51.67%
83.7K

Serialization is to store the tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from a file.

serialize-sdeserialize-binary-tree

Following are some simpler versions of the problem:

If given Tree is a Binary Search Tree?

If the given Binary Tree is Binary Search Tree, we can store it by either storing preorder or postorder traversal. In case of Binary Search Trees, only preorder or postorder traversal is sufficient to store structure information. 

If given Binary Tree is Complete Tree?

A Binary Tree is complete if all levels are completely filled except possibly the last level and all nodes of last level are as left as possible (Binary Heaps are complete Binary Tree). For a complete Binary Tree, level order traversal is sufficient to store the tree. We know that the first node is root, next two nodes are nodes of next level, next four nodes are nodes of 2nd level and so on. 

If given Binary Tree is Full Tree?

A full Binary is a Binary Tree where every node has either 0 or 2 children. It is easy to serialize such trees as every internal node has 2 children. We can simply store preorder traversal and store a bit with every node to indicate whether the node is an internal node or a leaf node.

How to store a general Binary Tree?

A simple solution is to store both Inorder and Preorder traversals. 

This solution requires space twice the size of the Binary Tree. We can save space by storing Preorder traversal and a marker for NULL pointers. 

  • Store all possible child nodes for each node.
  • If there is no child node then push -1 for that child.
  • Put this preorder traversal in the file.

Examples:

Input:
     12
    /
13
Output: 12 13 -1 -1 -1

Input:
      20
    /   \
8     22 
Output: 20 8 -1 -1 22 -1 -1 

Input:
         20
       /    
     8     
   /  \
4   12 
    /   \
10  14
Output: 20 8 4 -1 -1 12 10 -1 -1 14 -1 -1 -1 

Input:
            20
           /    
         8     
       /
   10
  /
5
Output: 20 8 10 5 -1 -1 -1 -1 -1 

Input:
          20
            \
             8
              \   
               10
                 \
                  5   

Output: 20 -1 8 -1 10 -1 5 -1 -1

How to deserialize the above serialization?

Deserialization can be done by simply reading data from the file one by one and keep on adding children till a -1 is reached. If both the children are NULL then return back to the parent.

Below is the implementation of the above idea.

C++




// A C++ program to demonstrate serialization and
// deserialization of Binary Tree
 
#include <bits/stdc++.h>
using namespace std;
 
#define MARKER -1
 
// A binary tree Node has key,
// pointer to left and right children
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Helper function that allocates a new Node with the
// given key and NULL left and right pointers.
struct Node* newNode(int key)
{
    struct Node* temp = new Node();
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// This function stores a tree in a file pointed by fp
void serialize(Node* root, FILE* fp)
{
    // If current node is NULL, store marker
    if (root == NULL) {
        fprintf(fp, "%d ", MARKER);
        return;
    }
 
    // Else, store current node and
    // recur for its children
    fprintf(fp, "%d ", root->key);
    serialize(root->left, fp);
    serialize(root->right, fp);
}
 
// This function constructs a tree from
// a file pointed by 'fp'
void deSerialize(Node*& root, FILE* fp)
{
    // Read next item from file.
    // If there are no more items
    // or next item is marker, then return
    int val;
    if (!fscanf(fp, "%d ", &val;) || val == MARKER)
        return;
 
    // Else create node with this item
    // and recur for children
    root = newNode(val);
    deSerialize(root->left, fp);
    deSerialize(root->right, fp);
}
 
// A simple inorder traversal used for
// testing the constructed tree
void inorder(Node* root)
{
    if (root) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}
 
// Driver code
int main()
{
    // Construct a tree shown in the above figure
    struct Node* root = newNode(20);
    root->left = newNode(8);
    root->right = newNode(22);
    root->left->left = newNode(4);
    root->left->right = newNode(12);
    root->left->right->left = newNode(10);
    root->left->right->right = newNode(14);
 
    // Open a file and serialize the tree into the file
    FILE* fp = fopen("tree.txt", "w");
    if (fp == NULL) {
        puts("Could not open file");
        return 0;
    }
    serialize(root, fp);
    fclose(fp);
 
    // Deserialize the stored tree into root1
    Node* root1 = NULL;
    fp = fopen("tree.txt", "r");
    deSerialize(root1, fp);
 
    printf("Inorder Traversal of the tree constructed from "
           "file:\n");
    inorder(root1);
 
    return 0;
}


Java




// A Java program to demonstrate serialization and
// deserialization of Binary Tree
 
import java.util.*;
 
// A binary tree Node has key,
// pointer to left and right children
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
 
class BinaryTree {
    TreeNode root;
 
    // Encodes a tree to a single string.
    public static String serialize(TreeNode root)
    {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
 
        List<String> l = new ArrayList<>();
        while (!s.isEmpty()) {
            TreeNode t = s.pop();
 
            // If current node is NULL, store marker
            if (t == null) {
                l.add("#");
            }
            else {
 
                // Else, store current node
                // and recur for its children
                l.add("" + t.val);
                s.push(t.right);
                s.push(t.left);
            }
        }
        return String.join(",", l);
    }
 
    static int t;
 
    // Decodes your encoded data to tree.
    public static TreeNode deserialize(String data)
    {
        if (data == null)
            return null;
        t = 0;
        String[] arr = data.split(",");
        return helper(arr);
    }
 
    public static TreeNode helper(String[] arr)
    {
        if (arr[t].equals("#"))
            return null;
 
        // Create node with this item
        // and recur for children
        TreeNode root
            = new TreeNode(Integer.parseInt(arr[t]));
        t++;
        root.left = helper(arr);
        t++;
        root.right = helper(arr);
        return root;
    }
 
    // A simple inorder traversal used
    // for testing the constructed tree
    static void inorder(TreeNode root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(root.val + " ");
            inorder(root.right);
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Construct a tree shown in the above figure
        BinaryTree tree = new BinaryTree();
        tree.root = new TreeNode(20);
        tree.root.left = new TreeNode(8);
        tree.root.right = new TreeNode(22);
        tree.root.left.left = new TreeNode(4);
        tree.root.left.right = new TreeNode(12);
        tree.root.left.right.left = new TreeNode(10);
        tree.root.left.right.right = new TreeNode(14);
 
        String serialized = serialize(tree.root);
        System.out.println("Serialized view of the tree:");
        System.out.println(serialized);
        System.out.println();
 
        // Deserialize the stored tree into root1
        TreeNode t = deserialize(serialized);
 
        System.out.println(
            "Inorder Traversal of the tree constructed"
            + " from serialized String:");
        inorder(t);
    }
}


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) { val = x; }
}
 
class BinaryTree {
    public TreeNode root;
 
    // Encodes a tree to a single string.
    public static string Serialize(TreeNode root)
    {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> s = new Stack<TreeNode>();
        s.Push(root);
 
        List<string> l = new List<string>();
        while (s.Count > 0) {
            TreeNode t = s.Pop();
 
            // If current node is NULL, store marker
            if (t == null) {
                l.Add("#");
            }
            else {
 
                // Else, store current node
                // and recur for its children
                l.Add(t.val.ToString());
                s.Push(t.right);
                s.Push(t.left);
            }
        }
        return string.Join(",", l);
    }
 
    static int t;
 
    // Decodes your encoded data to tree.
    public static TreeNode Deserialize(string data)
    {
        if (data == null)
            return null;
        t = 0;
        string[] arr = data.Split(',');
        return Helper(arr);
    }
 
    public static TreeNode Helper(string[] arr)
    {
        if (arr[t].Equals("#"))
            return null;
 
        // Create node with this item
        // and recur for children
        TreeNode root = new TreeNode(int.Parse(arr[t]));
        t++;
        root.left = Helper(arr);
        t++;
        root.right = Helper(arr);
        return root;
    }
 
    // A simple inorder traversal used
    // for testing the constructed tree
    static void Inorder(TreeNode root)
    {
        if (root != null) {
            Inorder(root.left);
            Console.Write(root.val + " ");
            Inorder(root.right);
        }
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        // Construct a tree shown in the above figure
        BinaryTree tree = new BinaryTree();
        tree.root = new TreeNode(20);
        tree.root.left = new TreeNode(8);
        tree.root.right = new TreeNode(22);
        tree.root.left.left = new TreeNode(4);
        tree.root.left.right = new TreeNode(12);
        tree.root.left.right.left = new TreeNode(10);
        tree.root.left.right.right = new TreeNode(14);
 
        string serialized = Serialize(tree.root);
        Console.WriteLine("Serialized view of the tree:");
        Console.WriteLine(serialized);
        Console.WriteLine();
 
        // Deserialize the// stored tree into root1
        TreeNode t = Deserialize(serialized);
 
        Console.WriteLine(
            "Inorder Traversal of the tree constructed"
            + " from serialized String:");
        Inorder(t);
    }
}
 
// This code is contributed by Potta Lokesh


Javascript




// A JavaScript program to demonstrate serialization and
// deserialization of Binary Tree
 
// Define the marker value
const MARKER = -1;
 
// A binary tree Node has key,
// pointer to left and right children
class Node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}
 
// Helper function that allocates a new Node with the
// given key and NULL left and right pointers.
function newNode(key) {
    let temp = new Node(key);
    return temp;
}
 
// This function stores a tree in a file pointed by fp
function serialize(root, fp) {
    // If current node is NULL, store marker
    if (root === null) {
        fp.push(MARKER);
        return;
    }
 
    // Else, store current node and
    // recur for its children
    fp.push(root.key);
    serialize(root.left, fp);
    serialize(root.right, fp);
}
 
// This function constructs a tree from
// a file pointed by 'fp'
function deSerialize(root, fp) {
    // Read next item from file.
    // If there are no more items
    // or next item is marker, then return
    let val = fp.shift();
    if (val === undefined || val === MARKER) {
        return null;
    }
 
    // Else create node with this item
    // and recur for children
    root = newNode(val);
    root.left = deSerialize(root.left, fp);
    root.right = deSerialize(root.right, fp);
    return root;
}
 
// A simple inorder traversal used for
// testing the constructed tree
function inorder(root) {
    if (root) {
        inorder(root.left);
        console.log(root.key);
        inorder(root.right);
    }
}
 
// Driver code
function main() {
    // Construct a tree shown in the above figure
    let root = newNode(20);
    root.left = newNode(8);
    root.right = newNode(22);
    root.left.left = newNode(4);
    root.left.right = newNode(12);
    root.left.right.left = newNode(10);
    root.left.right.right = newNode(14);
 
    // Open a file and serialize the tree into the file
    let fp = [];
    serialize(root, fp);
 
    // Deserialize the stored tree into root1
    let root1 = null;
    root1 = deSerialize(root1, fp);
 
    console.log("Inorder Traversal of the tree constructed from file:");
    inorder(root1);
 
    return 0;
}
 
main();


Python3




class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
 
class BinaryTree:
    def __init__(self):
        self.root = None
 
    # Encodes a tree to a single string.
    def serialize(self, root):
        if not root:
            return None
 
        stack = [root]
        l = []
 
        while stack:
            t = stack.pop()
 
            # If current node is NULL, store marker
            if not t:
                l.append("#")
            else:
                # Else, store current node
                # and recur for its children
                l.append(str(t.val))
                stack.append(t.right)
                stack.append(t.left)
 
        return ",".join(l)
 
    # Decodes your encoded data to tree.
    def deserialize(self, data):
        if not data:
            return None
 
        global t
        t = 0
        arr = data.split(",")
        return self.helper(arr)
 
    def helper(self, arr):
        global t
        if arr[t] == "#":
            return None
 
        # Create node with this item
        # and recur for children
        root = TreeNode(int(arr[t]))
        t += 1
        root.left = self.helper(arr)
        t += 1
        root.right = self.helper(arr)
        return root
 
    # A simple inorder traversal used
    # for testing the constructed tree
    def inorder(self, root):
        if root:
            self.inorder(root.left)
            print(root.val, end=" ")
            self.inorder(root.right)
 
# Driver code
if __name__ == '__main__':
    # Construct a tree shown in the above figure
    tree = BinaryTree()
    tree.root = TreeNode(20)
    tree.root.left = TreeNode(8)
    tree.root.right = TreeNode(22)
    tree.root.left.left = TreeNode(4)
    tree.root.left.right = TreeNode(12)
    tree.root.left.right.left = TreeNode(10)
    tree.root.left.right.right = TreeNode(14)
 
    serialized = tree.serialize(tree.root)
    print("Serialized view of the tree:")
    print(serialized)
    print()
 
    # Deserialize the stored tree into root1
    t = tree.deserialize(serialized)
 
    print("Inorder Traversal of the tree constructed from serialized String:")
    tree.inorder(t)


How much extra space is required in above solution?

If there are n keys, then the above solution requires n+1 markers which may be better than simple solution (storing keys twice) in situations where keys are big or keys have big data items associated with them.

Can we optimize it further?

The above solution can be optimized in many ways. If we take a closer look at the above serialized trees, we can observe that all leaf nodes require two markers. One simple optimization is to 

  • Store a separate bit with every node to indicate that the node is internal or external. 
  • This way we don’t have to store two markers with every leaf node as leaves can be identified by the extra bit. 
  • We still need a marker for internal nodes with one child. 

For example, in the following diagram, the character ‘ is used to indicate an internal node set bit, and ‘/‘ is used as NULL marker.

optimizedSerial

Please note that there are always more leaf nodes than internal nodes in a Binary Tree (Number of the leaf nodes is the number of internal nodes (with degree 2) plus 1, so this optimization makes sense.

How to serialize N-ary tree?

In an N-ary tree, there is no designated left or right child. We can store an ‘end of children‘ marker with every node. The following diagram shows serialization where ‘)’ is used as the end of the children marker. We will soon be covering implementation for N-ary tree.

serializeNaryTree



Similar Reads

Serialize and Deserialize an N-ary Tree
Given an N-ary tree where every node has the most N children. How to serialize and deserialize it? Serialization is to store a tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from the file. This post is mainly an extension of the below post. Serialize and Deseri
11 min read
Serialize and Deserialize array of string
We have given an array of string and we have to serialize the array of string and deserialize the serialized string. Examples: Input : "geeks", "are", "awesome"Output : Serialized String : 5~geeks3~are7~awesome Deserialized String : geeks are awesomeInput : "hello", "guys", "whats", "up!!!"Output : Serialized String : 5~hello4~guys5~whats5~up!!! De
5 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, wi
2 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
Given a tree having every node's value as either 0 or 1, the task is to find whether the given binary tree contains any sub-tree that has equal number of 0's and 1's, if such sub-tree is found then print Yes else print No.Examples: Input: Output: Yes There are two sub-trees with equal number of 1's and 0's. Hence the output is "Yes"Input: Output: N
10 min read
Difference between General tree and Binary tree
General Tree: In the data structure, General tree is a tree in which each node can have either zero or many child nodes. It can not be empty. In general tree, there is no limitation on the degree of a node. The topmost node of a general tree is called the root node. There are many subtrees in a general tree. The subtree of a general tree is unorder
2 min read
Tournament Tree (Winner Tree) and Binary Heap
Given a team of N players. How many minimum games are required to find the second-best player? We can use adversary arguments based on the tournament tree (Binary Heap). A Tournament tree is a form of min (max) heap which is a complete binary tree. Every external node represents a player and the internal node represents the winner. In a tournament
6 min read
Convert a given Binary tree to a tree that holds Logical AND property
Given a Binary Tree (Every node has at most 2 children) where each node has value either 0 or 1. Convert a given Binary tree to a tree that holds Logical AND property, i.e., each node value should be the logical AND between its children. Examples: Input : The below tree doesn’t hold the logical AND property convert it to a tree that holds the prope
7 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
15+ min read
Difference between Binary tree and B-tree
B-Tree : B-Tree is known as a self-balancing tree as its nodes are sorted in the inorder traversal. Unlike the binary trees, in B-tree, a node can have more than two children. B-tree has a height of logM N (Where ‘M’ is the order of tree and N is the number of nodes). And the height is adjusts automatically at each update. In the B-tree data is sor
7 min read
Difference between Binary Search Tree and AVL Tree
Binary Search Tree:A binary Search Tree is a node-based binary tree data structure that has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key.The right subtree of a node contains only nodes with keys greater than the node’s key.The left and right subtree each must also be a binary search t
2 min read
Check if a given Binary Tree is height balanced like a Red-Black Tree
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property. For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to lea
9 min read
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here. Example:Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the le
10 min read
Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Given a Complete Binary Tree as an array, the task is to print all of its levels in sorted order.Examples: Input: arr[] = {7, 6, 5, 4, 3, 2, 1} The given tree looks like 7 / \ 6 5 / \ / \ 4 3 2 1 Output: 7 5 6 1 2 3 4 Input: arr[] = {5, 6, 4, 9, 2, 1} The given tree looks like 5 / \ 6 4 / \ / 9 2 1 Output: 5 4 6 1 2 9 Approach: A similar problem is
6 min read
Check if the given n-ary tree is a binary tree
Given an n-ary tree, the task is to check whether the given tree is binary or not. Examples: Input: A / \ B C / \ \ D E F Output: Yes Input: A / | \ B C D \ F Output: No Approach: Every node in a binary tree can have at most 2 children. So, for every node of the given tree, count the number of children and if for any node the count exceeds 2 then p
6 min read
Convert a given Binary tree to a tree that holds Logical OR property
Given a Binary Tree (Every node has at most 2 children) where each node has value either 0 or 1. The task is to convert the given Binary tree to a tree that holds Logical OR property, i.e., each node value should be the logical OR between its children. Example: Input: 1 / \ 1 0 / \ / \ 0 1 1 1 Output: 0 1 1 1 1 1 1Explanation: Given Tree 1 / \ 1 0
7 min read