I have a list of integers that I want to convert into a binary tree, in Python. Each element should go to the next available position in the tree, going from left to right.
For example, the list of integers could be
root = [3,9,20,None,None,15,7]
If a node is None, then I want that node to be ignored when considering where to put a list element. So for the list
root = [2,None,3,None,4,None,5,None,6]
each element goes on its own level. (This array representation of binary trees come from Leetcode eg (https://leetcode.com/problems/minimum-depth-of-binary-tree/).)
I can solve the problem when the list is exhaustive, ie each position in the tree is specified, even if it's parent(s) are None; see below.
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def array_to_binary_tree(array):
n = len(array)
node = Node(array[0])
nodes = []
nodes.append(node)
for i in range(0, n):
left_index = i * 2 + 1
if left_index < n:
node_left = Node(array[left_index])
nodes.append(node_left)
nodes[i].left = node_left
right_index = i * 2 + 2
if right_index < n:
node_right = Node(array[right_index])
nodes.append(node_right)
nodes[i].right = node_right
root = nodes[0]
return root
But I can't solve it for when the array is giving a minimalist representation.
root = [2,null,3,null,4,null,5,null,6]thenullmeansNoneI presume!?[2,None,3,None,4,None,5,None,6]a tree representation. Can you show the desired output?nullin the textual representation of a tree/node, which you’ve copy-pasted. Is there a specific LeetCode problem you’re trying to solve?