Lately, I started "leetcode" for studying programming. Sometimes, I encounter the question which is related to TreeNode. https://leetcode.com/problems/longest-univalue-path/
I usually run code in local to make sure if my code work. But those questions require me to prepare for TreeNode in advance, otherwise, I can not run in local. I don't know how to build TreeNode from a list.
I want to make TreeNode from a list by Python, like here.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
input: [5,4,5,1,1,5]
output:
TreeNode{val: 5, left: TreeNode{val: 4, left: TreeNode{val: 1, left: None, right: None}, right: TreeNode{val: 1, left: None, right: None}}, right: TreeNode{val: 5, left: TreeNode{val: 5, left: None, right: None}, right: None}}
I know we can make sure whether the code work or not on leetcode. However, I think it's slow for me to check the code on leetcode. I would like to run my code in local. I hope you will help me.
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)
Take a look at LeetCode's 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, you'll also need to write some code (or I'm sure you can find some online) that will input a serialized list, build the tree, and return the tree's root TreeNode so you can pass it to your find_longest_univalue_path
function.
Here is just beautified StefanPochmann 's solution which was described at LeetCode's Help Center
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return 'TreeNode({})'.format(self.val)
def deserialize(string):
if string == '[]':
return None
nodes = [None if val == 'null' else TreeNode(int(val))
for val in string.strip('[]').split(',')]
kids = nodes[::-1]
root = kids.pop()
for node in nodes:
if node:
if kids:
node.left = kids.pop()
if kids:
node.right = kids.pop()
return root
if __name__ == '__main__':
tree = deserialize('[3,9,20,null,null,15,7]')
assert tree == TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.