def main(): depth = 3 # depth of tree mean_ins = 6 # mean length of insertions var_ins = 4 # variance for length of insertions p_mutation = 0.001 # prob of a mutation (per base) p_del = 0.05 # prob of deletion mean_del = 4 # mean length of deletion var_del = 2 #variance for length of deletion #tree = gen_tree.generate_tree(depth, mean_ins, var_ins, p_mutation, p_del, mean_del, var_del) #leaves = tree[-1] #ai.entropy_leaves(leaves) # for leaf in leaves: # print gen_tree.stringify(leaf) # gen_tree.print_tree(tree) # try to generate multiple trees and figure out the mean/var of the entropies at each position. N = 100 # generate 100 trees. entropies = [[] for i in range(100)] max_length = 0 for i in range(N): print 'generating tree %s/%s' % (i, N) tree = gen_tree.generate_tree(depth, mean_ins, var_ins, p_mutation, p_del, mean_del, var_del) _, entropy, length, _ = ai.entropy_leaves(tree[-1]) for base_position in range(length): entropies[base_position].append(entropy[base_position]) max_length = max(max_length, length)
def main(): # should be able to cPickle this. depth = 5 # depth of tree mean_ins = 6 # mean length of insertions var_ins = 2 # variance for length of insertions p_mutation = 0.0 # prob of a mutation (per base) p_del = 0.0 # prob of deletion mean_del = 4 # mean length of deletion var_del = 2 #variance for length of deletion parser = OptionParser() parser.add_option('-f', dest='fname', help='name of pkl file') (options, args) = parser.parse_args() tree = gen_tree.generate_tree(depth, mean_ins, var_ins, p_mutation, p_del, mean_del, var_del) f = open(options.fname, 'wb') cPickle.dump(tree, f) f.close()
class Solution: def countPairs(self, root: TreeNode) -> int: res = [] def dfs(root, path, counter): if root: if counter <= 0: res.append(path) return if not root.left and not root.right: res.append(path) return else: dfs(root.left, path + [root.val], counter - root.val) dfs(root.right, path + [root.val], counter - root.val) dfs(root, [], 4) return res if __name__ == '__main__': s = Solution() # root = [1, None, 2, None, 3, None, 4, None, 5,] root = [1, 2, 3, 4, None, None, 5] from gen_tree import generate_tree tree = generate_tree(root) print(s.countPairs(tree))
class Solution: def increasingBST(self, root): self.res = [] self.inOrder(root) if not self.res: return dummy = TreeNode(-1) cur = dummy for node in self.res: node.left = node.right = None cur.right = node cur = cur.right return dummy.right def inOrder(self, root): if not root: return self.inOrder(root.left) self.res.append(root) self.inOrder(root.right) if __name__ == '__main__': s = Solution() root = [5, 3, 6, 2, 4, None, 8, 1, None, None, None, 7, 9] from gen_tree import generate_tree print(s.increasingBST(generate_tree(root)))
self.val = val self.left = left self.right = right class Solution: def __init__(self): self.ans_left = [] self.ans_right = [] def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree( p.right, q.right) if __name__ == '__main__': from gen_tree import generate_tree s = Solution() p = [10, 5, 15] q = [10, 5, None, None, 15] p_tree = generate_tree(p) q_tree = generate_tree(q) print(s.isSameTree(p_tree, q_tree))
#!/usr/bin/python3 # -*- coding:utf-8 -*- class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: def dfs(node, min_val, max_val): if not node: return True if not min_val < node.val < max_val: return False return dfs(node.left, min_val, node.val) and dfs( node.right, node.val, max_val) return dfs(root, float('-inf'), float('inf')) if __name__ == '__main__': s = Solution() root = [5, 1, 4, None, None, 3, 6] from gen_tree import generate_tree print(s.isValidBST(generate_tree(root)))
def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pseudoPalindromicPaths(self, root: TreeNode) -> int: self.ans = 0 def dfs(root, record): if root: record ^= (1 << root.val) # 计算有多少个不同的数字 if not (root.left or root.right): if bin(record).count("1") < 2: self.ans += 1 return dfs(root.left, record) dfs(root.right, record) dfs(root, 0) return self.ans if __name__ == '__main__': root = [2, 3, 1, 3, 1, None, 1] tree = (generate_tree(root)) s = Solution() print(s.pseudoPalindromicPaths(tree))
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.pre = 0 def convertBST(self, root: TreeNode) -> TreeNode: def dfs(root): if not root: return dfs(root.right) root.val += self.pre self.pre = root.val dfs(root.left) dfs(root) return root if __name__ == '__main__': s = Solution() root = [4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8] from gen_tree import generate_tree print(s.convertBST(generate_tree(root)))
self.right = right class Solution: def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode: def dfs(root, level, flag): # flag用来表示当前遍历到的节点是其双亲节点的左孩子节点还是右孩子节点 if root: # 不是根节点的状态 if level == d: # 到达了指定替换的行了 new_root = TreeNode(v) if not flag: new_root.left = root else: new_root.right = root return new_root root.left = dfs(root.left, level + 1, 0) root.right = dfs(root.right, level + 1, 1) return root return TreeNode(v) if level == d else None # 比较特殊 因为最后一行的下一行也可能是指定行 return dfs(root, 1, 0) if __name__ == '__main__': s = Solution() root = [4, 2, 6, 3, 1, 5] val = 1 depth = 2 from gen_tree import generate_tree print(s.addOneRow(generate_tree(root), val, depth))
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: self.ans = [] def dfs(root): if not root: return else: dfs(root.left) dfs(root.right) self.ans.append(root.val) dfs(root) return self.ans if __name__ == '__main__': from gen_tree import generate_tree s = Solution() root = [1, None, 2, 3] print(s.postorderTraversal(generate_tree(root)))
self.parents[root.right.val] = root get_parent(root.right) self.res = [] get_parent(root) def dfs(root, node, k): if k == 0: self.res.append(root.val) return if root.left and root.left != node: dfs(root.left, root, k - 1) if root.right and root.right != node: dfs(root.right, root, k - 1) if root.val in self.parents and self.parents[root.val] != node: dfs(self.parents[root.val], root, k - 1) dfs(target, None, k) return self.res if __name__ == '__main__': s = Solution() root = [3, 5, 1, 6, 2, 0, 8, None, None, 7, 4] target = 5 K = 2 from gen_tree import generate_tree print(s.distanceK(generate_tree(root), generate_tree([target]), K))
def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def findSecondMinimumValue(self, root: TreeNode) -> int: self.ans = set() def dfs(node): if node is not None: dfs(node.left) self.ans.add(node.val) dfs(node.right) dfs(root) res = sorted(list(self.ans)) if len(res) > 1: return res[1] return -1 if __name__ == '__main__': s = Solution() from gen_tree import generate_tree root = [2, 2, 5, None, None, 5, 7] print(s.findSecondMinimumValue(generate_tree(root)))
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: cnt, level_sum = [], [] def dfs(root, depth): if root: if len(cnt) < depth: cnt.append(0) level_sum.append(0) cnt[depth - 1] += 1 level_sum[depth - 1] += root.val dfs(root.left, depth + 1) dfs(root.right, depth + 1) dfs(root, 1) return [s / c for s, c in zip(level_sum, cnt)] if __name__ == '__main__': s = Solution() nums = [3, 9, 20, None, None, 15, 7] root = generate_tree(nums) print(s.averageOfLevels(root))
from collections import Counter class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: def dfs(root, pre, cnt): if not root: return 0 cnt += root.val ans = pre[cnt - sum] pre[cnt] += 1 if root.left: ans += dfs(root.left, pre, cnt) if root.right: ans += dfs(root.right, pre, cnt) pre[cnt] -= 1 return ans return dfs(root, Counter([0]), 0) if __name__ == '__main__': s = Solution() from gen_tree import generate_tree root = [10, 5, -3, 3, 2, None, 11, 3, -2, None, 1] targetSum = 8 print(s.pathSum(generate_tree(root), targetSum))