二叉树中和为某一值的路径
生活随笔
收集整理的這篇文章主要介紹了
二叉树中和为某一值的路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的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)
總結
以上是生活随笔為你收集整理的二叉树中和为某一值的路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 判断某数组是不是二叉树的前序遍历序列 p
- 下一篇: Dokcer启动2个mysql容器