列印樹的和的路徑

2021-10-08 12:03:22 字數 2665 閱讀 5310

給定乙個二叉樹,找到從根節點到葉子節點的和與給定目標相等的路徑

從根節點開始,遍歷每一條路徑,每走過乙個節點,就把目標值減去這個節點的值,當最後乙個節點沒有左右孩子且這個節點的值等於剩餘的目標值,就返回這個路徑,用乙個區域性list存當前路徑。

def

sum(self,target)

:return self.sum_helper(self.root,target)

defsum_helper

(self,node,target)

:if node is

none

:return

false

if node._left is

none

and node._right is

none

and node._item == target:

#if node._item == target:

return

true

target = target - node._item

return self.sum_helper(node._left,target)

or self.sum_helper(node._right,target)

defsum_road

(self,target)

:return self.sum_target_helper(self.root,target)

defsum_target_helper

(self,node,target)

:if node is

none

:return

res =

self.dfs(node,target,

,res)

return res

defdfs(self,node,target,ls,res)

:if node._left is

none

and node._right is

none

and node._item == target:

if node._left:

self.dfs(node._left,target-node._item,ls+

[node._item]

,res)

if node._right:

self.dfs(node._right,target-node._item,ls+

[node._item]

,res)

def

sum(self,target)

:return self.sum_helper(self.root,target)

defsum_helper

(self,node,target)

:if node is

none

:return

false

#if node._left is none and node._right is none and node._item == target:

if node._item == target:

return

true

target = target - node._item

return self.sum_helper(node._left,target)

or self.sum_helper(node._right,target)

defsum_road

(self,target)

:return self.sum_road_all(self.root,target)

#return self.sum_target_helper(self.root,target)

defsum_road_all

(self,node,target)

:if node is

notnone

:return self.sum_target_helper(node,target)

+self.sum_target_helper(node._left,target)

+self.sum_target_helper(node._right,target)

defsum_target_helper

(self,node,target)

:if node is

none

:return

res =

self.dfs(node,target,

,res)

return res

defdfs(self,node,target,ls,res)

:# if node._left is none and node._right is none and node._item == target:

if node._item == target:

if node._left:

self.dfs(node._left,target-node._item,ls+

[node._item]

,res)

if node._right:

self.dfs(node._right,target-node._item,ls+

[node._item]

,res)

列印二叉樹的路徑

本題源自leetcode 思路1 遞迴 先訪問根節點。然後遞迴遍歷左子樹和右子樹。遇到葉節點則儲存路徑。vectorbinarytreepaths treenode root void findpath treenode root,vector res,string s if root left i...

逃離迷宮的路徑 列印路徑

題目描述 現在有乙個5 5的迷宮,起點在左上角,終點在右下角,現在請你來寫乙個程式計算一下,lzy從起點開始走迷宮,最終能否成功的逃離迷宮?如果lzy可以逃出迷宮,請輸出逃離迷宮的最短路徑,否則輸出 no path 輸入 測試樣例由多組測試資料組成,每組測試資料輸入乙個5 5的矩陣,矩陣中只包含 0...

列印二叉樹和為某一值的路徑

struct btnode 思路 因為求路徑是從根節點到葉子結點,所以我們可以考慮二叉樹的先序遍歷框架,如下所示 void preorder btnode root 但是在二叉樹的遞迴框架中,回溯到父節點時我們是不能獲取到前面遞迴經過的路徑上的節點的值的,因為這些操作是系統自動用遞迴工作棧來完成的,...