日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

边工作边刷题:70天一遍leetcode: day 94-1

發布時間:2025/7/14 编程问答 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 边工作边刷题:70天一遍leetcode: day 94-1 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Largest BST Subtree

要點:

  • http://articles.leetcode.com/largest-binary-search-tree-bst-in
  • 這題重點是理解題意,還有道類似題 Largest Binary Search Tree (BST) in a Binary Tree – LeetCode( http://articles.leetcode.com/largest-binary-search-tree-bst-in_22
  • 兩題的區別:
    • 本題with all descendants:需要所有left/right子樹都是bst,并且和root構成bst。而另一題是如果left or right不是bst,root還可以是(這里注意即使不要求所有descendants,結點仍需要連接的才構成bst)
    • 顯然如果all descendants,需要檢查到最底才能決定,所以bottom up方法。而另一題要從上到下擴展,所以top-down。
  • return value和args:
    • 本題用bottom up的方法,所有min/max是return的,并且要return子樹的判定狀態和結點個數:-1表示子樹不是bst,0個結點還是可以的。其他個數要比較min/max和root。
      • 通過檢查-1/0來ignore返回的max/min:所以可以返回0/0作為max/min
    • 另一題return的個數是0或者實際個數,另外如果不能擴展了,要以這個子樹為root重新計數

錯誤點:

  • 不能因為left子樹不符合就提前返回,仍然要遍歷right子樹來找到其他root對應的bst subtree

https://repl.it/Cb9Z/2

# Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.# Note: # A subtree must include all of its descendants. # Here's an example: # 10 # / \ # 5 15 # / \ \ # 1 8 7 # The Largest BST Subtree in this case is the highlighted one. # The return value is the subtree's size, which is 3. # Hint:# You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity. # Follow up: # Can you figure out ways to solve it with O(n) time complexity?# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = Noneclass Solution(object):def largestBSTSubtree(self, root):""":type root: TreeNode:rtype: int"""def bfs(root):if not root:return 0,0,0isBST = Trueleftnodes, maxl, minl = bfs(root.left)if leftnodes==-1 or (leftnodes!=0 and root.val<maxl):isBST = Falseif leftnodes==0:minl = root.valrightnodes, maxr, minr = bfs(root.right)if rightnodes==-1 or (rightnodes!=0 and root.val>minr):isBST = Falseif rightnodes==0:maxr = root.valif isBST:self.maxLen = max(self.maxLen, leftnodes+rightnodes+1)return leftnodes+rightnodes+1, maxr, minlreturn -1, 0, 0self.maxLen = 0bfs(root)return self.maxLen

轉載于:https://www.cnblogs.com/absolute/p/5815850.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的边工作边刷题:70天一遍leetcode: day 94-1的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。