[Python] Best way to construct a binary tree from a list in python

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    Assuming each node has self.left, self.right and self.data, whats the best way to construct a binary tree, not a binary search tree (BST), from a list where the numbers are given per level. Where the first number is level 1, next 2 are level 2, next 4 are level 3, and so on. For example

    input: [3,5,2,1,4,6,7,8,9,10,11,12,13,14]


    constructs a tree:

    3
    / \
    5 2
    /\ /\
    1 4 6 7
    /\ /\ /\ /\
    8 9 10 11 12 13 14


    One solution is:

    for node at index i,
    left child index = 2i+1
    right child index = 2i+2


    Wondering if there are other possible ways

    Continue reading...

Compartilhe esta Página