How do I make TreeNode from list by Python
How do I make TreeNode from list by Python
Take a look at LeetCodes official explanation https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation- of how their serialized formatting of a binary tree into the kind of list you see in their test cases works. If you want to run your solution against those test cases locally, youll also need to write some code (or Im sure you can find some online) that will input a serialized list, build the tree, and return the trees root TreeNode so you can pass it to your find_longest_univalue_path
function.
Guess this is what you need:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def creatBTree(data, index):
pNode = None
if index < len(data):
if data[index] == None:
return
pNode = TreeNode(data[index])
pNode.left = creatBTree(data, 2 * index + 1) # [1, 3, 7, 15, ...]
pNode.right = creatBTree(data, 2 * index + 2) # [2, 5, 12, 25, ...]
return pNode
Say you are cracking pathSum, populate the tree by calling
lst = [5,4,8,11,None,13,4,7,2,None,None,None,1]
root = creatBTree(lst, 0)