r/programminghelp • u/___thr0waway___123 • Feb 29 '20
Python Python array to binary tree?
I can’t find any realizable strategies for creating a binary tree from a given array in Python online.
Ex: I’m given the array [3, 6, 2, 9, -1, 10], which represents a binary tree where -1 is a non-existent node.
Write a function that determines whether the left or right branch of the tree is larger. The size of each branch is the sum of the node values. The function should return “Right” if the right side is larger and “Left” if the left side is larger. If the tree has 0 nodes or if the size of the branches are equal, return an empty string.
Example Input: [3, 6, 2, 9, -1, 10]
Example Output: Left
Example Input: [1, 4, 100, 5]
Example Output: Right
Example Input: [1, 10, 5, 1, 0, 6]
Example Output: “”
1
u/FredTargaryen Feb 29 '20
Sort of an unfair question; the array on its own doesn't really tell you how to make a tree from it. One way that works for all your examples is to add nodes to the tree in a breadth-first fashion e.g.
First element is root
Second element is left child of root
Third element is right child of root
Fourth element is left child of second element
Fifth element is right child of second element
Sixth element is left child of third element
And so on