码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Largest BST Subtree"

时间:2016-02-12 15:09:18      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!