@author: sdubrz
@date: 8/2/2020 2:54:10 PM
难度: 中等
考察内容: 二叉树
@e-mail: lwyz521604#163.com
题目来自《剑指offer》 电子工业出版社
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
- 节点总数 <= 10000
解法
判断以 root 节点为根的二叉树中是否有和为 sum 的路径,就是判断 root 的左子树和右子树中是否有和为 sum-root.val 的路径。根据这一思路,可以写出递归的实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> list = new LinkedList<>();
if(root==null) {
return list;
}
if(root.val==sum && root.left==null && root.right==null) {
List<Integer> tempList = new LinkedList<>();
tempList.add(root.val);
list.add(tempList);
return list;
}
if(root.left!=null) {
List<List<Integer>> leftList = pathSum(root.left, sum-root.val);
Iterator<List<Integer>> iter = leftList.iterator();
while(iter.hasNext()) {
List<Integer> tempList = iter.next();
tempList.add(0, root.val);
list.add(tempList);
}
}
if(root.right!=null) {
List<List<Integer>> rightList = pathSum(root.right, sum-root.val);
Iterator<List<Integer>> iter = rightList.iterator();
while(iter.hasNext()) {
List<Integer> tempList = iter.next();
tempList.add(0, root.val);
list.add(tempList);
}
}
return list;
}
}
在 LeetCode 系统中提交的结果为
执行结果:通过 显示详情
执行用时:2 ms, 在所有 Java 提交中击败了37.96%的用户
内存消耗:40 MB, 在所有 Java 提交中击败了72.31%的用户