# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution: defsubtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: rowList = list() rowSet = set() rowSet.add(root) rowList.append(rowSet) while(1): newRowSet = set() for each in rowSet: if each.left: newRowSet.add(each.left) if each.right: newRowSet.add(each.right) if newRowSet: rowList.append(newRowSet) rowSet = newRowSet else: break iflen(rowList) == 1: return root lastSet = rowList[-1] iflen(lastSet) == 1: return lastSet.pop() ans = None for i, eachSet inenumerate(rowList[-2::-1]): newLastSet = set() for eachNode in eachSet: if eachNode.left in lastSet or eachNode.right in lastSet: newLastSet.add(eachNode) iflen(newLastSet) == 1: ans = newLastSet.pop() return ans else: lastSet = newLastSet return ans;