def helper(lower=float('-inf'), higher=float('inf')): if not data or data[-1] < lower or data[-1] > higher: return None val = data.pop() root = TreeNode(val) root.right = helper(val, higher) root.left = helper(lower, val) return root
def longestConsecutive(self, root: TreeNode) -> int: self.cnt = 0 self.helper(root, 1) return self.cnt def helper(self, root: TreeNode, parentCnt): if root == None: return if root.left != None: if (root.left.val > root.val): parentCnt += 1 self.cnt = max(self.cnt, parentCnt) self.helper(root.left, parentCnt) else: self.helper(root.left, 1) if root.right != None: if (root.right.val > root.val): parentCnt += 1 self.cnt = max(self.cnt, parentCnt) self.helper(root.right, parentCnt) else: self.helper(root.right, 1) if __name__ == '__main__': S = Solution() root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(4) root.left.left = TreeNode(6) print(S.longestConsecutive(root))
class Solution(object): def flipEquiv(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: bool """ if root1 is root2: return True if not root1 or not root2 or root1.val != root2.val: return False return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or ( self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left)) if __name__ == '__main__': S = Solution() root = TreeNode(5) root.left = TreeNode(2) root.right = TreeNode(3) root.right.right = TreeNode(4) root2 = TreeNode(5) root2.right = TreeNode(2) root2.left = TreeNode(3) root2.left.right = TreeNode(4) print(S.flipEquiv(root, root2))
val = root.val val += dps(root.left) val += dps(root.right) freq[val]+=1 return val dps(root) r = sorted(freq.items(),key =lambda p:p[1],reverse=True) return [ k for k,v in r if v == r[0][1]] def test(self): d = {'art': 'van gogh', 'opera': 'carmen'} # Set value in current context #d['x'] # Get first key in the chain of contexts #del d['x'] # Delete from current context #list(d) # All nested values #k in d # Check all nested values ''' print(len(d)) # Number of nested values print(d.items()) # All nested items for k in d.items(): print(k) ''' if __name__ == '__main__': S = Solution() root = TreeNode(5) root.left = TreeNode(2) root.right = TreeNode(-3) #root.left.left = TreeNode(10) print(S.findFrequentTreeSum(root))