题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
class Solution:
def FindPath(self , root: TreeNode, target: int) -> List[List[int]]:
# write code here
if root == None:
return
res = self.mySolution(root, target)
return res
def mySolution1(self, root, target):
# 迭代-前序遍历
# 通过
st = []
pair = [root, root.val,[root.val]]
st.append(pair)
res = []
while len(st):
pair = st.pop()
if pair[0].left == None and pair[0].right == None and pair[1] == target:
res.append(pair[2])
if pair[0].right:
st.append([pair[0].right, pair[1] + pair[0].right.val, pair[2] + [pair[0].right.val]])
if pair[0].left:
st.append([pair[0].left, pair[1] + pair[0].left.val, pair[2] + [pair[0].left.val]])
return res
def mySolution(self, root, target):
# 递归-前序遍历
self.res = []
def preOrder(root, sum1, path):
if root == None:
return
if root.left == None and root.right == None and sum1 == root.val:
self.res.append(path)
return
if root.left == None and root.right == None:
return
if root.left:
preOrder(root.left, sum1-root.val, path+[root.left.val])
if root.right:
preOrder(root.right, sum1-root.val, path+[root.right.val])
return
preOrder(root, target, [root.val])
return self.res


查看27道真题和解析