SHARE
TWEET

Untitled

a guest Apr 26th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
  2.  
  3. * solution1: Recursion
  4. ```python3
  5. # -*- coding:utf-8 -*-
  6. # class TreeNode:
  7. #     def __init__(self, x):
  8. #         self.val = x
  9. #         self.left = None
  10. #         self.right = None
  11. class Solution:
  12.     # 返回二维列表,内部每个列表表示找到的路径
  13.         def FindPath(self, root, expectNumber):
  14.         # write code here
  15.         res = []
  16.         if not root:
  17.             return res
  18.            
  19.             def find_path_main(root,path,expectNumber):
  20.                 if not root:
  21.                     return res
  22.                 path.append(root.val)
  23.                 expectNumber -= root.val
  24.                 if expectNumber == 0 and root.left == None and root.right == None:
  25.                     res.append([val for val in path])
  26.                 find_path_main(root.left,path,expectNumber)
  27.                 find_path_main(root.right,path,expectNumber)
  28.                 path.pop()
  29.                 return res
  30.         res = find_main_path(root,[],expectNumber)
  31.         return res
  32.    
  33. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top