Update 二叉树相关.md

master
Omooo 4 years ago
parent 899c7a89ac
commit 3325d740d6
  1. 29
      blogs/Algorithm/剑指 Offer/二叉树相关.md

@ -165,3 +165,32 @@ class Solution {
}
```
#### [ Offer 34. 二叉树中和为某一值的路径](https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/)
```java
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
path(root, sum);
return result;
}
private void path(TreeNode root, int sum) {
if (root == null) {
return;
}
path.add(root.val);
int target = sum - root.val;
if (target == 0 && root.left == null && root.right == null) {
result.add(new ArrayList(path));
}
path(root.left, target);
path(root.right, target);
path.remove(path.size() - 1);
}
}
```

Loading…
Cancel
Save