bfs 和 dfs 彙總

1.dfs(深度優先搜索)就是暴力把所有的路徑都搜索出來,它運用了回溯,保存這次的位置,深入搜索,都搜索完了便回溯回來,搜下一個位置,直到把所有最深位置都搜一遍,要注意的一點是,搜索的時候有記錄走過的位置,標記完後可能要改回來;也可以遞歸處理左右子節點,不需要回溯

257. 二叉樹的所有路徑

給定一個二叉樹,返回所有從根節點到葉子節點的路徑。

class Solution:
    def dfs(self,root,path,result):
        if not root:
            return
        path += str(root.val)
        if not root.left and not root.right:
            result.append(path[:])
        else:
            path+="->"
            self.dfs(root.left,path,result)
            self.dfs(root.right,path,result)

    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        result = []
        self.dfs(root,"",result)
        return result

 

 

 

2.bfs(寬度/廣度優先搜索),這個一直理解了思想,不會用,後面纔會的,思想,從某點開始,走四面可以走的路,然後在從這些路,在找可以走的路,直到最先找到符合條件的,這個運用需要用到隊列(queue),需要稍微掌握這個才能用bfs。

199. 二叉樹的右視圖

給定一棵二叉樹,想象自己站在它的右側,按照從頂部到底部的順序,返回從右側所能看到的節點值。

層序遍歷取出每層的最後一個節點

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        # BFS
        if not root:
            return []
        result = []
        queue = [root]

        while queue:
            result.append(queue[-1].val)
            size = len(queue)
            for i in range(0,size):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return result

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章