Solution 1: accepted
BFS.
- two queues
- one queue + one flag node
- one queue + int size (chosen)
|
|
BFS.
|
|
BFS. Viration of question 102.Try recursive as well.
|
|
Time: O(n)
Space: O(1) (O(h) if the stack space is considered)
```java
class Solution {
// consider to use a class Type to record the value
static int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPath(root);
int temp = max;
max = Integer.MIN_VALUE;
return temp;
}
public int maxPath(TreeNode root) {
if (root == null) {
return 0;
} else {
// divide
int left = maxPath(root.left);
int right = maxPath(root.right);
// conquer
max = Math.max(max, root.val + left + right);
return Math.max(0, root.val + Math.max(0, Math.max(left, right)));
}
}
}
������java
class Solution {
public List
List
List
traverse(result, path, root);
return result;
}
private void traverse(List<String> result, List<Integer> path, TreeNode root) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
result.add(formatList(path));
} else {
traverse(result, path, root.left);
traverse(result, path, root.right);
}
path.remove(path.size() - 1);
}
private String formatList(List<Integer> path) {
StringBuilder sb = new StringBuilder();
sb.append(path.get(0));
for (int i = 1; i < path.size(); i++) {
sb.append("->" + path.get(i));
}
return sb.toString();
}
}
������
|
|
|
|
|
|
Brute force is not working.
|
|
Binary method.
|
|
Use long to avoid MAX and MIN checks.
|
|
DFS.
|
|
|
|
|
|
DFS, similar to question 078.
|
|
DFS. Follow-up of 078 Subset.
|
|