Enumerate all subtrees of tree s, and check whether the subtree is equal to t.
public class Solution { public boolean isSubtree(TreeNode s, TreeNode t) { if (s == null) { return t == null; } else if (t == null) {…
Simple recursion is okay.
public class Solution { static class Result { int sum; int titlSum; public Result(final int sum, final int titlSum) { this.sum = sum; this.titlSum = titlSum; } }…
Simple recursion problem.
For each non-null node, output the node value, if all its children are non-null, we are done, otherwise, append parenthesis and recurse on left child, if the right child is null, its parenthesis can be omitted…
We can simply enumerate all potential pairs, which costs O(mn).
public String[] findRestaurant(String[] list1, String[] list2) { List<String> ret = new ArrayList<>(); int minSum = list1.length + list2.length; for (int i…
Just a procedural problem. Do it according to the definition.
d == 1
d > 1
d — 1
Make sure you understand the problem:
|a-b|
The obvious solution is to enumerate all possible solutions which costs O(n³). 1000³ = 10⁹ will produce a TLE. For faster lookup, we can always sort it and using binary search.
Assume the three sides are a, b, c where a <= b <= c. If we’ve known a and b…
a <= b <= c
A tree problem.
It’s naturally to solve it recursively. Just be attention for the base cases.
public class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null) { return t2…
Actually, this is a math problem.
For simplicity, assume ai < bi, and it’s naturally to make <ai, bi> consecutive such that sumOf(ai) will be the largest.
They’re almost the same: