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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

二叉树中和为某一值的路径

發布時間:2023/11/28 生活经验 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉树中和为某一值的路径 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)

python 非遞歸做法

利用后序遍歷的非遞歸思想

class Solution:# 返回二維列表,內部每個列表表示找到的路徑def FindPath(self, root, expectNumber):to_visit = []cur = rootlast_node = Noneres, path = [], []while cur or len(to_visit) != 0:if cur:to_visit.append(cur)path.append(cur.val)cur = cur.leftelse:top_node = to_visit[-1]if top_node.right and last_node != top_node.right:cur = top_node.rightelse:if sum(path) == expectNumber and top_node.left is None and top_node.right is None:res.append([value for value in path])to_visit.pop()path.pop()last_node = top_nodereturn res

解析

之所以要在上面的代碼中加上last_node是為了在遍歷了右子樹之后不會再反復的遍歷右子樹而是遍歷父親節點

python 遞歸做法

class Solution:# 返回二維列表,內部每個列表表示找到的路徑def FindPath(self, root, expectNumber):res = []if root is None:return resdef find_path_main(root, path, expectNumber):if root is None:return respath.append(root.val)expectNumber -= root.valif expectNumber == 0 and root.left is None and root.right is None:res.append([value for value in path])find_path_main(root.left, path, expectNumber)find_path_main(root.right, path, expectNumber)path.pop()return resres = find_path_main(root, [], expectNumber)return res

在中間使用遞歸的時候,由于res是全局變量,所以不將返回值賦值也是無所謂的,我們完全可以將return 后面什么也不跟也是可以得,然后,在外層返回res,就像下面這樣:


class Solution:# 返回二維列表,內部每個列表表示找到的路徑def FindPath(self, root, expectNumber):res = []if root is None:return resdef find_path_main(root, path, expectNumber):if root is None:returnpath.append(root.val)expectNumber -= root.valif expectNumber == 0 and root.left is None and root.right is None:res.append([value for value in path])find_path_main(root.left, path, expectNumber)find_path_main(root.right, path, expectNumber)path.pop()return find_path_main(root, [], expectNumber)return res

衍生一題

如果只要你判斷是不是存在,而不是存在路徑,是不是可以更加簡單一些呢?leetcode有一題:
112. Path Sum

class Solution:def hasPathSum(self, root, sum):"""Given a binary tree and a sum,determine if the tree has a root-to-leaf pathsuch that adding up all the values along the path equals the given sum.:type root: TreeNode:type sum: int:rtype: bool"""if not root:return Falseif not root.left and not root.right and root.val == sum:return True# minus the val every travel timessum -= root.valreturn self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)

總結

以上是生活随笔為你收集整理的二叉树中和为某一值的路径的全部內容,希望文章能夠幫你解決所遇到的問題。

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