(Translated by https://www.hiragana.jp/)
davidgao7.github.io/_posts/2021-10-05-binary-tree-path-sum.md at master · davidgao7/davidgao7.github.io · GitHub
Skip to content

Latest commit

 

History

History
115 lines (87 loc) · 3.11 KB

2021-10-05-binary-tree-path-sum.md

File metadata and controls

115 lines (87 loc) · 3.11 KB
title date permalink tags
Binary Tree Path Sum
2021-09-24
/posts/2021/09/path-sum/
binary tree
depth first search
breath first search

题目描述

给定一个节点数为 n てき二叉树和一个值 sum ,请找所有しょゆうてき节点いたかのう节点てき节点值之とう于的みち,如果ぼつゆう则返かいそら

れい如: 给出如下てきまた树,sum = 22 ,

given: binary tree

return

[
  [5,4,11,2],
  [5,8,9]
]

Space complexity: O(n)

Time complexity: O(n)

かい题思

题目そう让你一条一条路径找到和为sumてきみち们,わが们学过的bfs(breath first search) かず dfs(depth first search) 趁现在来ざいらい复习いち

Here's the definition of BFS (ch 22.2 Introduction to Algorithms):

Given a graph G = (V,E) and a distinguished source vertex s, breadth-first search systematically explores the edges of G to 'discover' every vertex that is reachable from s.

“找到のうどおりこう罗马てき所有しょゆう

BFS作用さよう: For any vertex v reachable from s, the simple path in the breadth-first tree from s to v corresponds to a shortest path from s to v in G.

Here is how bfs process

bfs mov

BFS逻辑おもえ

given: G = (V,E) with adjacency lists of weights bfs alg

scanning adjacency lists: O(E)
queue operation: O(V)
BFS: O(V+E)

DFS逻辑おもえTo search "deeper" in the graph whenever possible.

DFS 找到最近さいきん经历てき vertex v, 找到あずか v 连接てき所有しょゆう edges。一直找直到我们找到了所有能从原点出发 reach いたてき vertices。

如果ゆう一些没有找到的vertices, dfs 继续选择另一个vertexとうさくsource, 继续じゅう复dfs

DFS 一直重复到它发现了所有的 vertex

DFS作用さよう

Here is how dfs process

dfs mov

DFS逻辑:

dfs alg

Enqueuing / Dequeuing : O(1)
Queue operation : O(V)
Scanning adjacency lists: O(E)
DFS: O(V+E)
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# @param root TreeNode类
# @param sum intせいがた
# @return intせいがた维数组
#
class Solution:
    def pathSum(self , root , sum ):
        # write code here
        temp,res=[],[]

        def dfs(root,sum,cnt):
            if not root: return #如果节点为空结束とうぜん递归
            temp.append(root.val) #はたとうぜん节点加入かにゅうtempすう
            cnt += root.val #とうぜん节点加入かにゅういたみちみちちゅう
            if root.left == None and root.right == None: #とう递归到ぼつ有子ゆうこ树的时候就需よう判断はんだん
                if cnt == sum:res.append(temp[:]) #如果とうぜん节点てきみちとう于sum,么就ざいresちゅう插入そうにゅうtmp
            else:
                dfs(root.left,sum,cnt) #递归ひだり
                dfs(root.right,sum,cnt) #递归右子ゆうこ

            cnt -= temp[len(temp) - 1]
            temp.pop()

        dfs(root,sum,0)
        return res

❗️ PS. function inside function in python, inside funtion can use the variable outside