I: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and
Given the below binary tree and
sum = 22, 5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path
5->4->11->2 which sum is 22.
DFS:
public class Solution {
//Time: O(n)
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
return checkPath(root, root.val, sum);
}
private boolean checkPath(TreeNode root, int cur, int sum) {
if (root.left == null && root.right == null) {
if (cur == sum) {
return true;
}
return false;
}
boolean left = false;
boolean right = false;;
if (root.left != null) {
left = checkPath(root.left, cur + root.left.val, sum);
}
if (root.right != null) {
right = checkPath(root.right, cur + root.right.val, sum);
}
return left || right;
}
}
BFS:
public class Solution {
//Time: O(n)
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Queue<Integer> queueSum = new LinkedList<Integer>();
queue.offer(root);
queueSum.offer(root.val);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
int cursum = queueSum.poll();
if (cur.left != null) {
queue.offer(cur.left);
queueSum.offer(cursum + cur.left.val);
}
if (cur.right != null) {
queue.offer(cur.right);
queueSum.offer(cursum + cur.right.val);
}
if (cur.left == null && cur.right == null && cursum == sum) {
return true;
}
}
return false;
}
}
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
DFS:
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return res;
}
ArrayList<Integer> tmp = new ArrayList<Integer>();
path(res, tmp, root, sum);
return res;
}
private void path(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp,
TreeNode root, int sum) {
if (root.left == null && root.right == null) {
tmp.add(root.val);
if (sum == root.val) {
res.add(new ArrayList(tmp));
}
tmp.remove(tmp.size() - 1);
return;
}
tmp.add(root.val);
if (root.left != null) {
path(res, tmp, root.left, sum - root.val);
}
if (root.right != null) {
path(res, tmp, root.right, sum - root.val);
}
tmp.remove(tmp.size() - 1);
}
}
No comments:
Post a Comment