def gen_random_tx(q, p, g): transaction = "*** Bitcoin transaction ***\n" serial_number = random.getrandbits(128) transaction += "Serial number: " + str(serial_number) + "\n" payerAlpha, payerBeta = DS.KeyGen(q, p, g) payeeAlpha, payeeBeta = DS.KeyGen(q, p, g) transaction += "Payer Public Key (beta): " + str(payerBeta) + "\n" transaction += "Payee Public Key (beta): " + str(payeeBeta) + "\n" amount = random.randint(1, 1000001) transaction += "Amount: " + str(amount) (s, r) = DS.SignGen(transaction.encode('UTF-8'), q, p, g, payerAlpha) transaction += "Signature (s): " + str(s) + "\n" transaction += "Signature (r): " + str(r) + "\n" return transaction
def CheckTransaction(q, p, g): tx = Tx.gen_random_tx(q, p, g) # generate a random transaction transaction = tx.split('\n') # Split it line by line payer_pk = int(transaction[2][25:]) # payer's publick key sign_s = int(transaction[5][15:]) # signature for the transaction (part s) sign_r = int(transaction[6][15:]) # signature for the transaction (part r) message2sign = '\n'.join(transaction[0:5])+'\n' if DS.SignVer(message2sign.encode('utf-8'), sign_s, sign_r, q, p, g, payer_pk)==0: return 0 else: return -1
def gen_random_tx(q, p, g): string = "*** Bitcoin transaction ***\n" # Key Generation phase (alpha1, beta1) = DS.KeyGen(q, p, g) # Keys of payer (alpha2, beta2) = DS.KeyGen(q, p, g) # Keys of payee serial = random.randint(0, 2**128 - 1) string += "Serial number: " + str(serial) + "\n" string += "Payer Public Key (beta): " + str(beta1) + "\n" string += 'Payee Public Key (beta): ' + str(beta2) + "\n" amount = random.randint(1, 1000000) string += "Amount: " + str(amount) + " Satoshi" + "\n" #assigning s and r keys (s, r) = DS.SignGen(string.encode('UTF-8'), q, p, g, alpha1) string += "Signature (s): " + str(s) + "\n" string += "Signature (r): " + str(r) + "\n" #print(string) Bitcoin transaction can be seen here return string
def CheckTestSignatures(): f = open("TestSet.txt", "r") q = int(f.readline()) p = int(f.readline()) g = int(f.readline()) beta = int(f.readline()) for i in range(0, 10): message = f.readline().rstrip("\n") s = int(f.readline()) h = int(f.readline()) ReturnCode = DS.SignVer(message.encode('UTF-8'), s, h, q, p, g, beta) if ReturnCode != 0: f.close() return -1 f.close() return 0
def CheckBlockofTransactions(): f = open("transactions.txt", "r") tx_block = f.readlines() f.close() if len(tx_block)%7 != 0: print("Incorrect file format") else: tx_block_count = len(tx_block)//7 result = [0]*tx_block_count for i in range(0, tx_block_count): pk = int(tx_block[i*7+2][24:]) s = int(tx_block[i*7+5][15:]) r = int(tx_block[i*7+6][15:]) tx = "".join(tx_block[i*7: i*7+5]) result[i] = DS.SignVer(tx.encode('UTF-8'), s, r, q, p, g, pk) return result
def gen_random_tx(q, p, g): serialNo = random.getrandbits(128) payerA, payerB = Func(q, p, g) payeeB = Func(q, p, g)[1] amount = random.randint(1, 1000000) Msg1 = '*** Bitcoin transaction ***' Msg2 = 'Serial number: ' + str(serialNo) Msg3 = 'Payer public key (beta): ' + str(payerB) Msg4 = 'Payee public key (beta): ' + str(payeeB) Msg5 = 'Amount: ' + str(amount) m = '\n'.join([Msg1, Msg2, Msg3, Msg4, Msg5]) s, r = DS.SignGen(m.encode('UTF-8'), q, p, g, payerA) sMsg = 'Signature (s): ' + str(s) rMsg = 'Signature (r): ' + str(r) realMsg = '\n'.join([m, sMsg, rMsg]) return realMsg
def CheckBlock(filename, q, p, g): if os.path.isfile(filename): f = open(filename, "r") block = f.readlines() if len(block) % 6 != 0: print("Incorrect file format") return -10000 block_count = len(block) // 6 for i in range(0, block_count): pk = int(block[i * 6 + 2][24:]) s = int(block[i * 6 + 4][15:]) h = int(block[i * 6 + 5][15:]) tx = "".join(block[i * 6:i * 6 + 4]) ver = DS.SignVer(tx.encode('UTF-8'), s, h, q, p, g, pk) if ver == -1: return -i return 0 else: print("File does not exist") return -10000
def render(self, record_list=[], **kw): artwork_list = [] for record in record_list: artwork = DS.Artwork(*record) artwork_list.append(artwork) return fill_template(name=self.name, artwork_list=artwork_list, **kw)
def countNodes(self, root: TreeNode) -> int: # if the tree is empty if not root: return 0 d = self.compute_depth(root) # if the tree contains 1 node if d == 0: return 1 # Last level nodes are enumerated from 0 to 2**d - 1 (left -> right). # Perform binary search to check how many nodes exist. left, right = 1, 2**d - 1 while left <= right: pivot = left + (right - left) // 2 if self.exists(pivot, d, root): left = pivot + 1 else: right = pivot - 1 # The tree contains 2**d - 1 nodes on the first (d - 1) levels # and left nodes on the last level. return (2**d - 1) + left if __name__ == '__main__': sol = Solution() root = DS.arr2TreeNode([1, 2, 3, 4, 5, 6]) print(sol.countNodes(root))
from DS import TreeNode import DS class Solution: def invertTree(self, root: TreeNode) -> TreeNode: """ idea: recursive call, post order traversal, this gives us the left-sub-tree and the right-sub-tree, switch them, then return the node """ if not root: return None left_sub_tree, right_sub_tree = None, None if root.left: left_sub_tree = self.invertTree(root.left) if root.right: right_sub_tree = self.invertTree(root.right) root.left, root.right = right_sub_tree, left_sub_tree return root if __name__ == '__main__': test1 = DS.arr2TreeNode([4, 2, 7, 1, 3, 6, 9]) sol = Solution() res = sol.invertTree(test1) print(res)
class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: """ Idea: For each unique tree, assign it a unique id which is equal to the number of unique registered at that time By using a post order, the subtree can be represented as (val, left_id, right_id) Use two dicts, one to store id of each subtree, one for storing nodes that have the same id """ from collections import defaultdict tree_ids = defaultdict() id_node = defaultdict(list) tree_ids.default_factory = tree_ids.__len__ def post_order(node: TreeNode) -> int: if node: node_id = tree_ids[(node.val, post_order(node.left), post_order(node.right))] id_node[node_id].append(node) return node_id return -1 post_order(root) return [id_node[k][0] for k in id_node if len(id_node[k]) > 1] if __name__ == '__main__': sol = Solution() root = DS.arr2TreeNode([2, 1, 1]) r = sol.findDuplicateSubtrees(root) print(r)
class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: list_len = 0 node1 = None node2 = None ptr = head while ptr: list_len += 1 if list_len == k: node1 = ptr ptr = ptr.next k = list_len - k + 1 ptr = head iteration = 0 while ptr: iteration += 1 if iteration == k: node2 = ptr ptr = ptr.next node1.val, node2.val = node2.val, node1.val return head if __name__ == '__main__': sol = Solution() root = DS.arr2LinkedNode([1, 2, 3, 4, 5]) k = 2 print(sol.swapNodes(root, k))
self.right = right class Solution: def maxPathSum(self, root: TreeNode) -> int: """ Idea: Do a post order, in each level, the maximum path come from taking both legs as long as the sum of leg > 0. Return the maximum path that contains itself """ def post_order(node: TreeNode) -> int: if not node: return 0 left_val = post_order(node.left) right_val = post_order(node.right) self.res = max(self.res, node.val + max(0, left_val) + max(0, right_val)) return node.val + max(0, left_val, right_val) self.res = -2000 post_order(root) return self.res if __name__ == '__main__': sol = Solution() root = DS.arr2TreeNode([1, 2, 3]) root2 = DS.arr2TreeNode([-10, 9, 20, None, None, 15, 7]) print(sol.maxPathSum(root)) print(sol.maxPathSum(root2))
from DS import TreeNode import DS class Solution: def findTarget(self, root: TreeNode, k: int) -> bool: """ Idea: do any kind of traversal and store the used number in hashmap """ values = set() def preorder(node: TreeNode) -> bool: if not node: return False if k - node.val in values: return True else: values.add(node.val) return preorder(node.left) or preorder(node.right) return preorder(root) if __name__ == '__main__': sol = Solution() r = DS.arr2TreeNode([2, 1, 3]) k = 3 print(sol.findTarget(r, k))
# Testing part # Test public parameters ReturnCode = checkDSparams(q, p, g) if ReturnCode == 0: print("Public parameters: Passed!") elif ReturnCode == -1: print("q is not prime") elif ReturnCode == -2: print("p is not prime") elif ReturnCode == -3: print("q does not divide p") elif ReturnCode == -4: print("g is not a generator") (alpha, beta) = DS.KeyGen(q, p, g) # generate key pair ReturnCode = CheckKeys(q, p, g, alpha, beta) if ReturnCode == 0: print("Public/private key pair: Passed!") else: print("Public/private key pair: Failed!") ReturnCode = CheckSignature(q, p, g, alpha, beta) if ReturnCode == 0: print("Signature generation: Passed!") else: print("Signature generation: Failed!") if (CheckTestSignatures() == 0): print("Sample signature test: Passed!")
return end, start res = ListNode() res.next = head prev = res ptr = head depth = 0 while ptr: if depth == k - 1: n = ptr.next head, tail = reverse(prev.next, ptr) prev.next = head tail.next = n prev = ptr ptr = n depth = 0 else: ptr = ptr.next depth += 1 return res.next if __name__ == '__main__': sol = Solution() head = DS.arr2LinkedNode([1, 2, 3, 4, 5]) k = 2 print(sol.reverseKGroup(head, k))
tx_block_count = len(tx_block)//7 result = [0]*tx_block_count for i in range(0, tx_block_count): pk = int(tx_block[i*7+2][24:]) s = int(tx_block[i*7+5][15:]) r = int(tx_block[i*7+6][15:]) break tx = "".join(tx_block[i*7: i*7+5]) result[i] = DS.SignVer(tx.encode('UTF-8'), s, r, q, p, g, pk) return result ##### This part executes # Generate or read the public parameters # You need to have a routine named GenerateOrRead that reads q, p, g from "pubparams.txt" if exists # Otherwise, it should generate public parameters and write them to "pubparams.txt" (q, p, g) = DS.GenerateOrRead("pubparams.txt") # DS.GenerateTestSignatures(q, p, g) # Generate sample signatures (Students do not uncomment this) # Testing part # Test 1: Test public parameters ReturnCode = checkDSparams(q, p, g) if ReturnCode == 0: print("Public parameters: Passed!") elif ReturnCode == -1: print("q is not prime"); sys.exit() elif ReturnCode == -2: print("p is not prime"); sys.exit() elif ReturnCode == -3: print("q does not divide p"); sys.exit() elif ReturnCode == -4: print("g is not a generator"); sys.exit() elif ReturnCode == -5: print("p is not 2048 bit"); sys.exit() elif ReturnCode == -6: print("q is not 224 bit"); sys.exit() # Test 2: Check a public-private key pair (alpha, beta) = DS.KeyGen(q, p, g) # generate key pair
for name in filename_list: if name.endswith('.xlsx'): sourcefile = '/Volumes/SSDData/PythonWork/DoubleSpikeMo/spkrunfiles/' + name with open(sourcefile, newline='', encoding="utf8") as MyFile: MyFile = pd.read_excel(sourcefile, header=None, names=header_list) MyFile.fillna(0, method=None, axis=1, inplace=True) k = len(MyFile) #scaling parameter1 l = len(header_list) #scaling parameter2 B = np.zeros([k, l]) #initiate scaled zero matrix B = MyFile.values #create numpy matrix from pandas DataFrame # send IP to data processing and write output file into ../Zn-DS/Results: #[bias] = DS.f(B) [invout, sprop, bias, dvalues] = DS.f(B) #add everything into 1 numpy 2-D array results = np.concatenate((invout, sprop, bias, dvalues), axis=1) #convert results into pandas dataframe results and append statistics using .describe() method on results cols = [ '92/98nat', '94/98nat', '95/98nat', '96/98nat', '97/98nat', '98/98nat', '100/98nat', '92/98mix', '94/98mix', '95/98mix', '96/98mix', '97/98mix', '98/98mix', '100/98mix', 'fspk', 'alpha', 'beta', 'd92/98Mo', 'd94/98Mo', 'd95/98Mo', 'd96/98Mo', 'd97/98Mo', 'd98/98Mo', 'd100/98Mo' ] results = pd.DataFrame(results, columns=cols) results = results.append(results.describe())
node_1.next = node_2 node_2.next = next_node tail = node_2 return result.next def swapPairs(self, head): """ From https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11019/7-8-lines-C%2B%2B-Python-Ruby Here, pre is the previous node. Since the head doesn't have a previous node, I just use self instead. Again, a is the current node and b is the next node. To go from pre -> a -> b -> b.next to pre -> b -> a -> b.next, we need to change those three references. Instead of thinking about in what order I change them, I just change all three at once. """ result = ListNode() pre, pre.next = result, head while pre.next and pre.next.next: a = pre.next b = a.next pre.next, b.next, a.next = b, a, b.next pre = a return result.next if __name__ == '__main__': sol = Solution() arr = [1, 2, 3] head = DS.arr2LinkedNode(arr) head = sol.swapPairs(head) DS.print_ListNode(head)
self.right = right class Solution: def minDepth(self, root: TreeNode) -> int: """ Idea: BFS, return the depth of the first leaf """ from collections import deque que = deque() if not root: return 0 que.appendleft((root, 1)) while que: curr, depth = que.pop() if not curr.left and not curr.right: return depth if curr.left: que.appendleft((curr.left, depth + 1)) if curr.right: que.appendleft((curr.right, depth + 1)) return -1 if __name__ == '__main__': test_head = DS.arr2TreeNode([3, 9, 20, None, None, 15, 7]) sol = Solution() test_head_2 = DS.arr2TreeNode([2, None, 3, None, 4, None, 5, None, 6]) print(sol.minDepth(test_head)) print(sol.minDepth(test_head_2))
it want to sand. For the parent node, it will gather the information from the subtrees and its own value then determine its condition based on the previous condition. """ self.res = 0 self.post_order(root) return self.res def post_order(self, node: TreeNode) -> int: """ :param node: current node to deal with :return: the number of coins needed """ left_condition = 0 right_condition = 0 if node.left: left_condition = self.post_order(node.left) if node.right: right_condition = self.post_order(node.right) self.res += (abs(left_condition) + abs(right_condition)) curr_condition = node.val + left_condition + right_condition return curr_condition - 1 if __name__ == '__main__': root_1 = DS.arr2TreeNode([1, 3, 0, 0, 0, 2, 1]) sol = Solution() print(sol.distributeCoins(root_1))
succ.left = None node.val += prev_val prev_val = node.val node = node.left return root def convertBST_rec(self, root: TreeNode) -> TreeNode: """ Idea: Do a reverse inorder traversal, each node.val = node.val + prev_val """ if root: self.prev_val = 0 self.rev_inorder(root) return root def rev_inorder(self, node): if node.right: self.rev_inorder(node.right) node.val += self.prev_val self.prev_val = node.val if node.left: self.rev_inorder(node.left) if __name__ == '__main__': root = DS.arr2TreeNode([4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8]) sol = Solution() sol.convertBST(root) print("solved")
def CheckSignature(q, p, g, alpha, beta): message = DS.random_string(random.randint(32, 512)).encode('UTF-8') # generate a random string for message and convert it to bytes (s, r) = DS.SignGen(message, q, p, g, alpha) return DS.SignVer(message, s, r, q, p, g, beta)
def render_edit_post(self, record, **kw): post = DS.Post(*record) return fill_template(name='blog_edit_post', post=post, **kw)
last_ptr = last prev = None while last_ptr: last_ptr.val += carry carry = last_ptr.val // 10 last_ptr.val %= 10 prev = last_ptr last_ptr = last_ptr.next if carry: prev.next = ListNode(carry) return self.reverse_LinkedList(last) def reverse_LinkedList(self, head: ListNode) -> ListNode: prev = None ptr = head while ptr: next_node = ptr.next ptr.next = prev prev = ptr ptr = next_node return prev if __name__ == '__main__': sol = Solution() a = DS.arr2LinkedNode([7, 2, 4, 3]) b = DS.arr2LinkedNode([5, 6, 4]) ans = sol.addTwoNumbers(a, b) print("Done")
def render_index(self, record_list=[]): post_list = [] for record in record_list: post = DS.Post(*record) post_list.append(post) return fill_template(name='blog_index', post_list=post_list)
def CheckSignature(q, p, g, alpha, beta): message = random_string(random.randint(32, 512)).encode('UTF-8') (s, h) = DS.SignGen(message, q, p, g, alpha) return DS.SignVer(message, s, h, q, p, g, beta)
def pdbtmparse(self, path): with open(path, "r") as files: lines = files.readlines() end.append(0) for i in range(len(lines)): if lines[i].startswith('</pdbtm>'): end.append(i) for j in range(len(end) - 1): pdbtm_dic = {} pdbtm_list = [] for z in range(end[j], end[j + 1]): if lines[z].startswith('<pdbtm '): pdbtmid = (lines[z].split(" ")[-2])[-5:-1] pdbtm_dic[pdbtmid] = pdbtm_list if lines[z].startswith(' <CREATE_DATE>'): create_date_dic = {} create_date = (lines[z].split(">")[1]).split("<")[0] create_date_dic['CREATE_DATE'] = create_date pdbtm_list.append(create_date_dic) elif lines[z].startswith(' <MODIFICATION>'): modification_list = [] modification_dic = {} if lines[z + 1].startswith(' <DATE>') and lines[ z + 2].startswith(' <DESCR>'): date_dic = {} descr_dic = {} date = (lines[z + 1].split(">")[1]).split("<")[0] descr = (lines[z + 2].split(">")[1]).split("<")[0] date_dic['DATE'] = date descr_dic['DESCR'] = descr modification_list.append(date_dic) modification_list.append(descr_dic) modification_dic[ 'MODIFICATION'] = modification_list pdbtm_list.append(modification_dic) elif lines[z].startswith(' <RAWRES>'): rawres_dic = {} rawres_list = [] rawres_dic['RAWRES'] = rawres_list pdbtm_list.append(rawres_dic) elif lines[z].startswith(' <TMRES>'): tmares_dic = {} tmares = (lines[z].split(">")[1]).split("<")[0] tmares_dic['TMRES'] = tmares rawres_list.append(tmares_dic) elif lines[z].startswith(' <TMTYPE>'): tmtype_dic = {} tmtype = (lines[z].split(">")[1]).split("<")[0] tmtype_dic['TMTYPE'] = tmtype rawres_list.append(tmtype_dic) elif lines[z].startswith(' <SPRES>'): spres_dic = {} spres = (lines[z].split(">")[1]).split("<")[0] spres_dic['SPRES'] = spres rawres_list.append(spres_dic) elif lines[z].startswith(' <PDBKWRES>'): pdbkwres_dic = {} pdbkwres = (lines[z].split(">")[1]).split("<")[0] pdbkwres_dic['PDBKWRES'] = pdbkwres rawres_list.append(pdbkwres_dic) elif lines[z].startswith(' <PDBKWORD>'): pdbkword_dic = {} pdbkword = (lines[z].split(">")[1]).split("<")[0] pdbkword_dic['PDBKWORD'] = pdbkword rawres_list.append(pdbkword_dic) elif lines[z].startswith(' <MEMBRANE>'): membrane_dic = {} membrane_list = [] membrane_dic['MEMBRANE'] = membrane_list pdbtm_list.append(membrane_dic) if lines[z + 1].startswith(' <NORMAL'): normal_dic = {} normal_list = [] normal_list.append( (lines[z + 1].split("L ")[1]).split("/")[0]) normal_dic['NORMAL'] = normal_list membrane_list.append(normal_dic) # print(normal_dic) if lines[z + 2].startswith(' <TMATRIX>'): tmatrix_dic = {} tmares_list = [] rowx_dic = {} rowy_dic = {} rowz_dic = {} rowx_dic['ROWX'] = ( lines[z + 3].split("X ")[1]).split("/")[0] rowy_dic['ROWY'] = ( lines[z + 4].split("Y ")[1]).split("/")[0] rowz_dic['ROWZ'] = ( lines[z + 5].split("Z ")[1]).split("/")[0] tmares_list.append(rowx_dic) tmares_list.append(rowy_dic) tmares_list.append(rowz_dic) tmatrix_dic['TMATRIX'] = tmares_list membrane_list.append(tmatrix_dic) elif lines[z].startswith(' <SIDEDEFINITION'): sidedefinition_dic = {} sidedefinition_list = [] note_dic = {} sidedefinition_list.append( (lines[z].split("N ")[1]).split(">")[0]) note_dic['NOTE'] = ( lines[z + 1].split("<NOTE>")[1]).split("<")[0] sidedefinition_list.append(note_dic) sidedefinition_dic[ 'SIDEDEFINITION'] = sidedefinition_list pdbtm_list.append(sidedefinition_dic) elif lines[z].startswith(' <BIOMATRIX>'): biomatrix_dic = {} biomatrix_list = [] biomatrix_dic['BIOMATRIX'] = biomatrix_list pdbtm_list.append(biomatrix_dic) elif lines[z].startswith(' <MATRIX '): matrix_dic = {} matrix_list = [] matrixid = lines[z].split('"')[1] matrix_dic[matrixid] = matrix_list biomatrix_list.append(matrix_dic) elif lines[z].startswith(' <APPLY_TO_CHAIN'): apply_to_chain_dic = {} apply_to_chain_dic['APPLY_TO_CHAIN'] = (lines[z].split( '<APPLY_TO_CHAIN ')[1]).split('/')[0] matrix_list.append(apply_to_chain_dic) elif lines[z].startswith(' <TMATRIX>'): tmatrix_list2 = [] tmatrix_dic2 = {} rowx_dic2 = {} rowy_dic2 = {} rowz_dic2 = {} rowx_dic2['ROWX'] = ( lines[z + 1].split("X ")[1]).split("/")[0] rowy_dic2['ROWY'] = ( lines[z + 2].split("Y ")[1]).split("/")[0] rowz_dic2['ROWZ'] = ( lines[z + 3].split("Z ")[1]).split("/")[0] tmatrix_list2.append(rowx_dic2) tmatrix_list2.append(rowy_dic2) tmatrix_list2.append(rowz_dic2) tmatrix_dic2['TMATRIX'] = tmatrix_list2 matrix_list.append(tmatrix_dic2) elif lines[z].startswith(' <DELETE '): delete_dic = {} delete_dic['DELETE'] = ( lines[z].split('<DELETE ')[1]).split('/')[0] biomatrix_list.append(delete_dic) elif lines[z].startswith(' <CHAIN'): chain_dic = {} chain_list = [] chain_list.append( (lines[z].split('<CHAIN ')[1]).split('\n')[0]) chain_dic['CHAIN'] = chain_list pdbtm_list.append(chain_dic) elif lines[z].startswith(' <SEQ>'): seq_dic = {} seq_list = [] seq = '' for m in range(1, 30): if lines[z + m].startswith(' </SEQ>'): break else: seq += (lines[z + m].lstrip()).split('\n')[0] seq_list.append(seq) seq_dic['SEQ'] = seq_list chain_list.append(seq_dic) elif lines[z].startswith(' <REGION '): region_dic = {} region_dic['REGION'] = ( lines[z].split(' <REGION ')[1]).split('/')[0] chain_list.append(region_dic) # return pdbtm_dic a = DS.DataStorage('PDBTM') a.Storage(pdbtm_dic) # def main(): # pdbtm = PDBTMParse() # pdbtm.pdbtmparse('C:/Users/jiayj/Desktop/pdbtmall.xml') # # if __name__ == '__main__': # main()
def render_post(self, record): post = DS.Post(*record) print(post.subject) return fill_template(name='blog_post', post=post)
class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: """ Idea: The maximum distance is length_of_left + length_of_right """ self.res = -float("inf") def dfs(node: TreeNode) -> int: """ returns the length of the leg """ if node: left_len = dfs(node.left) right_len = dfs(node.right) self.res = max(self.res, left_len + right_len) return 1 + max(left_len, right_len) else: return 0 dfs(root) return self.res if self.res != -float("inf") else 0 if __name__ == '__main__': sol = Solution() r = DS.arr2TreeNode([1, 2, 3, 4, 5]) print(sol.diameterOfBinaryTree(r))