714518. Construct a Full Binary Tree

Medium

Construct a Full Binary Tree

Summary

Constructing a full binary tree involves creating a tree where each node has at most two children (left and right). This problem requires us to create such a tree given a list of nodes, ensuring that each node has exactly one parent.

The key concepts involved are tree data structures and algorithms, specifically traversal and manipulation techniques.

Detailed Explanation

To construct a full binary tree from the given list of nodes, we will use an in-order traversal technique. The idea is to insert the middle element from the sorted array as the root of the tree, then recursively create the left and right subtrees.

Here's a step-by-step breakdown of the solution:

  1. Sort the array of nodes.
  2. Find the middle element (i.e., the median) in the sorted array. This will be the root of our full binary tree.
  3. Create a new node with the value of the middle element and add it to the tree as the root.
  4. Recursively construct the left subtree by calling the function on the elements before the middle element, and the right subtree by calling the function on the elements after the middle element.
  5. Repeat steps 2-4 until all nodes have been inserted into the tree.

Here's an ASCII art diagram to illustrate this process:

       3 (root)
     /        \
   1         4
  / \       / \
 0   2   5   6

Time complexity: O(n log n) due to sorting, where n is the number of nodes. Space complexity: O(1), as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public class FullBinaryTree {
    public static Node construct(Node[] nodes) {
        Arrays.sort(nodes);
        return constructTree(nodes, 0, nodes.length - 1);
    }

    private static Node constructTree(Node[] nodes, int start, int end) {
        if (start > end) {
            return null;
        }
        int mid = start + (end - start) / 2;
        Node root = new Node(nodes[mid]);
        root.left = constructTree(nodes, start, mid - 1);
        root.right = constructTree(nodes, mid + 1, end);
        return root;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.