Question:
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target
.
A valid path is from root node to any of the leaf nodes.
Example:
Given a binary tree, and target = 5
:
1
/ 2 4
/ 2 3
return
[
[1, 2, 2],
[1, 4]
]
Analysis:
先序遍历整棵树,用一个变量sum记录从根节点到当前节点的节点数字之和,当遇到叶子节点(节点左右子节点均为空)并且和等于目标target的时候,该条路径就是我们要找的路径,将它加入到list当中。
递归函数helper的定义:在当前节点至叶子节点所有的路径中找出符合条件的路径加入到结果集当中。
Code:
1 public class Solution { 2 /** 3 * @param root the root of binary tree 4 * @param target an integer 5 * @return all valid paths 6 */ 7 public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { 8 List<List<Integer>> list = new ArrayList<>(); 9 List<Integer> path = new ArrayList<Integer>(); 10 11 if(root == null) { 12 return list; 13 } 14 15 path.add(root.val); 16 helper(root, root.val, target, path, list); 17 return list; 18 } 19 20 private void helper(TreeNode root, 21 int sum, 22 int target, 23 List<Integer> path, 24 List<List<Integer>> list) { 25 if(root.left == null && root.right == null && sum == target) { 26 list.add(new ArrayList<Integer>(path)); 27 return; 28 } 29 30 if(root.left != null) { 31 path.add(root.left.val); 32 helper(root.left, sum + root.left.val, target, path, list); 33 path.remove(path.size() - 1); 34 } 35 36 if(root.right != null) { 37 path.add(root.right.val); 38 helper(root.right, sum + root.right.val, target, path, list); 39 path.remove(path.size() - 1); 40 } 41 } 42 }
Complexity:
时间复杂度为O(n),n为树中节点的个数。空间复杂度为O(h * 2^(h - 1)),h为树的高度。
时间: 2024-10-05 04:34:10