题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f
#两次遍历,循环迭代 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @param sum int整型 # @return int整型 # from queue import Queue class Solution: #paths=[] cur_patht=[] pathst=[] def FindPathx(self , root: TreeNode, sum: int): # write code here if not root: return [] cur_path=self.cur_patht cur_path.append(root) if root.val==sum: self.pathst.append(cur_path) if root.left: self.cur_patht=cur_path self.FindPathx(root.left, sum-root.val) if root.right: self.cur_patht=cur_path self.FindPathx(root.right, sum-root.val) def FindPath(self , root: TreeNode, sum: int) -> int: if not root: return 0 tq=Queue() tq.put(root) while tq.qsize(): node=tq.get() self.FindPathx(node, sum) if node.left: tq.put(node.left) if node.right: tq.put(node.right) return len(self.pathst)