) + 1 if root.left is None or root.right is None else min( self.minDepth(root.left), self.minDepth(root.right)) + 1 return res def minDepth2(self, root): res = 0 if root is None: return res q = deque([root]) while q: self.count += 1 n = len(q) for i in range(n): t = q.popleft() if t is not None: if t.left is None and t.right is None: return res + 1 q.extend([t.left, t.right]) res += 1 return res if __name__ == '__main__': s = Solution() li = [3, 9, 20, None, None, 15, 7] t = gen_tree(li) print(s.minDepth(t), s.count) s.count = 0 print(s.minDepth2(t), s.count)
global maxSum if child is None: return [1, sys.maxsize, -(sys.maxsize - 1), 0] left_li = traverse(child.left) right_li = traverse(child.right) res = [0 for i in range(4)] if left_li[0] == 1 and right_li[0] == 1 and child.val < right_li[ 1] and child.val > left_li[2]: res[0] = 1 res[1] = min(child.val, left_li[1]) res[2] = max(child.val, right_li[2]) res[3] = left_li[3] + right_li[3] + child.val maxSum = max(maxSum, res[3]) else: res[0] = 0 return res traverse(root) return maxSum if __name__ == '__main__': s = Solution() # li = [1, 4, 3, 2, 4, 2, 5, None, None, None, None, None, None, 4, 6] #20 # li = [4, 3, None, 1, 2] #2 # li = [2, 1, 3] #6 # li = [-4, -2, -5] # 0 li = [5, 4, 8, 3, None, 6, 3] # 7 root = ltn.gen_tree(li) print(s.maxSumBST(root))
def searchBST(tree: ltn.TreeNode): nonlocal count, max_c, prev, res if tree is None: return searchBST(tree.left) if prev is None: count = 1 elif prev.val == tree.val: count += 1 else: count = 1 prev = tree if count == max_c: res.append(tree.val) elif count > max_c: max_c = count res = [tree.val] searchBST(tree.right) return searchBST(root) return res if __name__ == '__main__': s = Solution() data = [6, 2, 8, 0, 4, 7, 9, None, None, 2, 6] t = ltn.gen_tree(data) print(s.findMode(t))
li.pop(0) li.pop(0) stack.append(None) stack.append(None) return root if t1 is None: return t2 if t2 is None: return t1 li1 = to_li(t1) li2 = to_li(t2) res = add_li(li1, li2) return to_tree(res) if __name__ == '__main__': sc = Solution() li1 = [ 4, -9, 5, None, -1, None, 8, -6, 0, 7, None, None, -2, None, None, None, None, -3 ] li2 = [5] t1 = gen_tree(li1) t2 = gen_tree(li2) t = sc.mergeTrees(t1, t2) print(print_tree(t, True)) t = sc.mergeTrees1(t1, t2) print(print_tree(t, True)) # [9,-9,5,null,-1,null,8,-6,0,7,null,null,-2,null,null,null,null,-3]