题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
1 import copy 2 class Solution: 3 # 返回二维列表,内部每个列表表示找到的路径 4 def FindPath(self, root, expectNumber): 5 # write code here 6 if root == None: 7 return [] 8 support = [root] 9 supportArrayList = [[root.val]] 10 ret=[] 11 while support: 12 tmpNode = support[0] 13 tmpArrayList=supportArrayList[0] 14 if tmpNode.left==None and tmpNode.right == None: 15 if sum(tmpArrayList)==expectNumber: 16 ret.insert(0,tmpArrayList) 17 if tmpNode.left: 18 support.append(tmpNode.left) 19 newtmpArrayList =copy.copy(tmpArrayList) 20 newtmpArrayList.append(tmpNode.left.val) 21 supportArrayList.append(newtmpArrayList) 22 if tmpNode.right: 23 support.append(tmpNode.right) 24 newtmpArrayList = copy.copy(tmpArrayList) 25 newtmpArrayList.append(tmpNode.right.val) 26 supportArrayList.append(newtmpArrayList) 27 del support[0] 28 del supportArrayList[0] 29 return ret
2019-12-15 09:28:59
原文地址:https://www.cnblogs.com/NPC-assange/p/12042019.html
时间: 2024-11-08 12:02:37