@@ -676,42 +676,41 @@ def findMaxLength(self, nums: List[int]) -> int:
676676############# 426. Convert Binary Search Tree to Sorted Doubly Linked List #############
677677class Solution :
678678 def treeToDoublyList (self , root : 'Optional[Node]' ) -> 'Optional[Node]' :
679- def dfs (node ):
680- """
681- Performs standard inorder traversal:
682- left -> node -> right
683- and links all nodes into DLL
684- """
685- nonlocal last , first
686- if node :
687- # left
688- dfs (node .left )
689-
690- # node
691- if last :
692- # link the previous node (last)
693- # with the current one (node)
694- last .right = node
695- node .left = last
696- else :
697- # keep the smallest node
698- # to close DLL later on
699- first = node
700- last = node
701-
702- # right
703- dfs (node .right )
704-
679+ """
680+ 思路:输入是bst,所以可以利用中序遍历 guarantee 访问的顺序是从小到大的。
681+ 利用一个 last 指针指向上个中序遍历节点,将其和当前node节点连接
682+ 再利用一个 first 指针指向第一个(最小)节点,在所有遍历完成之后将其和 last 指针互相连接完成闭环
683+ """
705684 if not root :
706685 return None
707686
708- # the smallest (first) and the largest (last) nodes
709687 first , last = None , None
710- dfs (root )
688+ def dfs (node ):
689+ """
690+ 1. 递归调用 node.left
691+ 2. 将当前节点 node 和上一个中序遍历节点 last 连接起来 或赋值 first 指针。
692+ 每次中序遍历总是更新 last 指针指向当前node
693+ 3. 递归调用 node.right
711694
712- # close DLL
713- last .right = first
695+ 返回值:不需要返回任何值,所有修改节点指针操作均为 in-place
696+ """
697+ nonlocal first
698+ nonlocal last
699+ if not node :
700+ return
701+ dfs (node .left )
702+ if last :
703+ last .right = node
704+ node .left = last
705+ else :
706+ first = node
707+ last = node
708+ dfs (node .right )
709+ return
710+
711+ dfs (root )
714712 first .left = last
713+ last .right = first
715714 return first
716715
717716
@@ -785,6 +784,33 @@ def removeDuplicates(self, s: str) -> str:
785784
786785 return '' .join (stack )
787786
787+ ############ 207. Course Schedule ############
788+ from collections import defaultdict
789+ class Solution :
790+ def canFinish (self , numCourses : int , prerequisites : List [List [int ]]) -> bool :
791+ mapping = defaultdict (list ) # prerequisite => descendant
792+
793+ def dfs (course , mapping , visiting ):
794+ if course in visiting :
795+ return False # cycle detected
796+ if len (mapping [course ]) == 0 : # no descendant
797+ return True
798+
799+ visiting .add (course )
800+ for desc in mapping [course ]:
801+ if not dfs (desc , mapping , visiting ): return False
802+ visiting .remove (course )
803+ mapping [course ] = []
804+
805+ return True
806+
807+ for a , b in prerequisites :
808+ mapping [b ].append (a )
809+ visiting = set ()
810+ for i in range (numCourses ):
811+ if not dfs (i , mapping , visiting ):
812+ return False
813+ return True
788814
789815############# 116. Populating Next Right Pointers in Each Node II #############
790816
0 commit comments