LeetCode刷题实战113:路径总和 II
共 3004字,需浏览 7分钟
·
2020-12-06 20:45
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children.
题意
解题
class Solution {
List<List> ret = new LinkedList<List >();
Dequepath = new LinkedList ();
public List<List> pathSum(TreeNode root, int sum) {
dfs(root, sum);
return ret;
}
public void dfs(TreeNode root, int sum) {
if (root == null) {
return;
}
path.offerLast(root.val);
sum -= root.val;
if (root.left == null && root.right == null && sum == 0) {
ret.add(new LinkedList(path));
}
dfs(root.left, sum);
dfs(root.right, sum);
path.pollLast();
}
}
方法二:广度优先搜索
class Solution {
List> ret = new LinkedList
>();
Mapmap = new HashMap ();
public List> pathSum(TreeNode root, int sum) {
if (root == null) {
return ret;
}
QueuequeueNode = new LinkedList ();
QueuequeueSum = new LinkedList ();
queueNode.offer(root);
queueSum.offer(0);
while (!queueNode.isEmpty()) {
TreeNode node = queueNode.poll();
int rec = queueSum.poll() + node.val;
if (node.left == null && node.right == null) {
if (rec == sum) {
getPath(node);
}
} else {
if (node.left != null) {
map.put(node.left, node);
queueNode.offer(node.left);
queueSum.offer(rec);
}
if (node.right != null) {
map.put(node.right, node);
queueNode.offer(node.right);
queueSum.offer(rec);
}
}
}
return ret;
}
public void getPath(TreeNode node) {
Listtemp = new LinkedList ();
while (node != null) {
temp.add(node.val);
node = map.get(node);
}
Collections.reverse(temp);
ret.add(new LinkedList(temp));
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。