def train(self, X_train, y_train, epochs=10, retrain=0, batch_size=1, loss_update=10): cum_loss = 0 history = {} losses = [] def get_progress(num, den, length): """ simple progress bar """ if num == den - 1: return '=' * length arrow = int(float(num) / den * length) return '=' * (arrow - 1) + '>' + '.' * (20 - arrow) # preprocess inputs and outputs print 'preprocessing inputs and outputs...' for i in tqdm(range(len(X_train))): X_train[i] = self.str_to_deptree(X_train[i]) root = Tree(formula=y_train[i]) y_train[i] = [ self.tar_vocab.sent_to_idx(formula) for formula in root.inorder() ] for epoch in range(retrain, epochs): epoch_loss = 0 print 'Epoch %d/%d' % (epoch, epochs) for i in range(len(X_train)): if i + batch_size > len(X_train): continue # NOTE: batch size forced to 1 loss = self.run_epoch(X_train[i], y_train[i], batch_size=1) cum_loss += loss epoch_loss += loss progress = get_progress(i, len(X_train), length=20) out = '%d/%d [%s] loss: %f' % (i, len(X_train), progress, epoch_loss / (i + 1)) sys.stdout.write('{0}\r'.format(out)) sys.stdout.flush() print losses.append(epoch_loss) if epoch % loss_update == 0: self.save('%s_epoch_%d.json' % (self.sess, epoch)) history['losses'] = losses return history
class Solution: def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 self.deepest_path = 0 def dfs(node): if node == None: return 0 left_depth = dfs(node.left) right_depth = dfs(node.right) self.deepest_path = max(self.deepest_path, left_depth + right_depth + 1) return 1 + max(left_depth, right_depth) dfs(root) return self.deepest_path - 1 if __name__ == "__main__": solution = Solution() t1 = Tree([1, 2, 3, 4, 5, None, None]).root print(solution.diameterOfBinaryTree(t1)) t2 = Tree([1]).root print(solution.diameterOfBinaryTree(t2))
def setUp(self): self.solution = Solution() self.testCase1 = Tree([3, 9, 20, None, None, 15, 7])
return 0 return self.dfs(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum) class Solution(object): # using hashmap def pathSum(self, root, target): """ :type root: TreeNode :type target: int :rtype: int """ self.count = 0 preDict = {0: 1} def dfs(p, target, pathSum, preDict): if p: pathSum += p.val self.count += preDict.get(pathSum - target, 0) preDict[pathSum] = preDict.get(pathSum, 0) + 1 dfs(p.left, target, pathSum, preDict) dfs(p.right, target, pathSum, preDict) preDict[pathSum] -= 1 dfs(root, target, 0, preDict) return self.count if __name__ == "__main__": solution = Solution() tree1 = [10,5,-3,3,2,None,11,3,-2,None,1] t1 = Tree(tree1).root sum = 8 print(solution.pathSum(t1, sum))
from tree_utils import Tree class Solution(object): def reload_the_set(self, root, unique_ele): unique_ele.add(root.val) if root.left: self.reload_the_set(root.left, unique_ele) if root.right: self.reload_the_set(root.right, unique_ele) if not root.left and not root.right: return def findSecondMinimumValue(self, root): """ :type root: TreeNode :rtype: int """ unique_eles = set() self.reload_the_set(root, unique_eles) sorted_set = sorted(unique_eles) if len(sorted_set)<=1: return -1 else: return sorted_set[1] if __name__ == "__main__": solution = Solution() tree1 = Tree([2, 2, 5, None, None, 5, 7]) print(solution.findSecondMinimumValue(tree1.root)) tree2 = Tree([2,2,2]) print(solution.findSecondMinimumValue(tree2.root))
result = [] cur_last_node = root next_last_node = root level_sum = 0 level_nodes_num = 0 queue = [] queue.insert(0, root) while len(queue) != 0: cur_node = queue.pop() if cur_node.left: next_last_node = cur_node.left queue.insert(0, cur_node.left) if cur_node.right: next_last_node = cur_node.right queue.insert(0, cur_node.right) level_sum += cur_node.val level_nodes_num += 1 if cur_node is cur_last_node: cur_last_node = next_last_node result.append(level_sum / level_nodes_num) level_nodes_num = 0 level_sum = 0 return result if __name__ == '__main__': solution = Solution() tree = Tree([3, 9, 20, 15, 17]) tree.viewTreeBFS() print(solution.averageOfLevels(tree.root))
def train(self, X_train, y_train, epochs=10, retrain=0, batch_size=10, loss_update=10): cum_loss = 0 history = {} losses = [] def get_progress(num, den, length): """ simple progress bar """ if num == den - 1: return '=' * length arrow = int(float(num) / den * length) return '=' * (arrow - 1) + '>' + '.' * (20 - arrow) for epoch in range(retrain, epochs): epoch_loss = 0 print 'Epoch %d/%d' % (epoch, epochs) for i in range(0, len(X_train), batch_size): X_batch = X_train[i:i + batch_size] if len(X_batch) < batch_size: continue if epoch == 0: # initialize training data to trees for j in range(i, i + batch_size): root = Tree(formula=y_train[j]) y_train[j] = [ self.tar_vocab.sent_to_idx(formula) for formula in root.inorder() ] X_batch = torch.tensor(X_batch, dtype=torch.long, device=self.device) y_batch = y_train[i:i + batch_size] loss = self.run_epoch(X_batch, y_batch, batch_size=batch_size) cum_loss += loss epoch_loss += loss progress = get_progress(i, len(X_train), length=20) out = '%d/%d [%s] loss: %f' % (i, len(X_train), progress, epoch_loss / (i + 1)) sys.stdout.write('{0}\r'.format(out)) sys.stdout.flush() print losses.append(epoch_loss) if epoch % loss_update == 0: self.save('%s_epoch_%d.json' % (self.sess, epoch)) history['losses'] = losses return history
def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ queue = [root] cur_last_node = root next_last_node = root result = root.val while len(queue) != 0: cur_node = queue.pop(0) if cur_node.right: queue.append(cur_node.right) next_last_node = cur_node.right if cur_node.left: queue.append(cur_node.left) next_last_node = cur_node.left if cur_node is cur_last_node: cur_last_node = next_last_node result = cur_node.val return result if __name__ == '__main__': solution = Solution() t1 = Tree([1, 2, 3, 4, None, 5, 6, 7]) print(solution.findBottomLeftValue(t1.root)) t2 = Tree([2, 1, 3]) print(solution.findBottomLeftValue(t2.root))
class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ self.unique_set = set() def dfs(cur_node): if cur_node: self.unique_set.add(cur_node.val) dfs(cur_node.left) dfs(cur_node.right) dfs(root) return sorted(self.unique_set)[k - 1] class Solution2(object): def kthSmallest(self, root, k): pass from tree_utils import Tree if __name__ == "__main__": solution = Solution() tree = [1] t = Tree(tree).root print(solution.kthSmallest(t, 1))
result.append(max(x.val for x in queue if x.val is not None)) temp_queue = [] for node in queue: if node.left != None: temp_queue.append(node.left) if node.right != None: temp_queue.append(node.right) queue = temp_queue return result class Solution2: def largestValues(self, root): row = [root] result = [] while any(row): result.append(max(x.val for x in row)) # this is not valide, the intereter could not find the definition of node # row = [kid for kid in (node.left, node.right) if kid for node in row ] row = [ kid for node in row for kid in (node.left, node.right) if kid ] return result if __name__ == "__main__": solution = Solution() tree = Tree([1, 3, 2, 5, 3, None, 9]) print(solution.largestValues(tree.root))
""" :type root: TreeNode :rtype: List[int] """ if not root: return [] cur_ptr = root next_right = root cur_right = root result = [] que = [root] while que: cur_ptr = que.pop(0) if cur_ptr.left: que.append(cur_ptr.left) next_right = cur_ptr.left if cur_ptr.right: que.append(cur_ptr.right) next_right = cur_ptr.right if cur_ptr == cur_right: result.append(cur_ptr.val) cur_right = next_right return result if __name__ == "__main__": s = Solution() t = [1, 2, 3, None, 5, None, 4] root = Tree.genTree(t) s.rightSideView(root)