标签:
A typical recursion use:
class Solution(object): max_size = 0 # return: isValid, minVal, maxVal, nodeCnt def go(self, root): if root.left is None and root.right is None: #print (root.val, True, root.val, root.val, 1) self.max_size = max(self.max_size, 1) return True, root.val, root.val, 1 leftOk = rightOk = True leftMin = leftMax = rightMin = rightMax = root.val leftCnt = rightCnt = 0 if root.left: leftValid, leftMin, leftMax, leftCnt = self.go(root.left) leftOk = leftValid and leftMax < root.val if root.right: rightValid, rightMin, rightMax, rightCnt = self.go(root.right) rightOk = rightValid and rightMin > root.val if leftOk and rightOk: self.max_size = max(self.max_size, leftCnt + rightCnt + 1) #print (root.val, leftOk and rightOk, leftMin, rightMax, leftCnt + rightCnt + 1) return leftOk and rightOk, leftMin, rightMax, leftCnt + rightCnt + 1 def largestBSTSubtree(self, root): if root is None: return self.max_size self.go(root) return self.max_size
LeetCode "Largest BST Subtree"
标签:
原文地址:http://www.cnblogs.com/tonix/p/5187027.html