LeetCode - Path Sum II

Question Definition

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example: Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

Java Solution

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root == null) return new LinkedList<>();
        List<List<Integer>> result = new LinkedList<>();
        List<Integer> cur = new LinkedList<>();
        dfs(root, sum, cur, result);
        return result;
    }

    private void dfs(TreeNode root, int sum, List<Integer> cur, List<List<Integer>> result) {
        if(root == null){
            return;
        }
        cur.add(root.val);
        if(root.left == null && root.right == null && root.val == sum){
            result.add(new LinkedList<>(cur));
            cur.remove(cur.size() - 1);
            return;
        }
        dfs(root.left, sum - root.val, cur, result);
        dfs(root.right, sum - root.val, cur, result);
        cur.remove(cur.size() - 1);
    }
}

LeetCode - Lowest Common Ancestor of a Binary Tree

Question Definition

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Java Solution

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || p == root || q == root) return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p , q);
    if (left != null && right != null) return root;
    return left != null ? left : right;
}