题目描述

输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

  1. # -*- coding:utf-8 -*-
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. # 返回二维列表,内部每个列表表示找到的路径
  9. def FindPath(self, root, expectNumber):
  10. # write code here
  11. res = []
  12. path = []
  13. def recur(root,tar):
  14. if not root:
  15. return None
  16. path.append(root.val)
  17. tar -=root.val
  18. if (tar==0) and not root.left and not root.right:
  19. res.append(list(path))
  20. recur(root.left,tar)
  21. recur(root.right,tar)
  22. path.pop()
  23. recur(root,expectNumber)
  24. return res