Let's say I have the following binary tree:
and the following TreeNode definition:
class TreeNode:
def __init__(self, x, left: = None, right: = None):
self.val = x
self.left = left
self.right = right
To construct this tree, I currently need to write the following code:
def build_tree() -> TreeNode:
node0 = TreeNode(2, left=TreeNode(4), right=TreeNode(5))
node1 = TreeNode(3, right=TreeNode(7))
root = TreeNode(1, left=node0, right=node1)
return root
This is very inefficient for large trees. Leetcode gives me trees as a Python list. For the example above, it reads:
[1, 2, 3, 4, 5, None, 7]
I would love to refactor build_tree so it takes a list, builds the tree and returns the root node:
def build_tree(values: list) -> ListNode:
...
Any ideas on how to create this function?
Here's a more complicated example:
[4, 6, 2, None, 5, 1, 9, 2, 1, 3, 4, None, 7]

