leetcode 题目链接
1. 题目考点
- String == 和 equals() 区别
- dfs 和 bfs 的变形
2. 考点解析
- == 比较两个变量所引用的
对象的地址
,equals() 比较的是两个对象的字面量
String s1 = "hello";
String s2 = "hello";
String s3 = s1;
String s4 = new String("hello");
s1 == s2
s3 == s1
s1 == s4
s1.equals(s4);
- dfs 的变形,要用上一个函数的结果,需要
添加一个参数
,通过参数传递给下一个函数
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
dfs(root, "", paths);
return paths;
}
public void dfs(TreeNode root, String path, List<String> paths) {
if (root != null) {
StringBuffer pathSB = new StringBuffer(path);
pathSB.append("" + root.val));
if (root.left == null && root.right == null) {
paths.add(pathSB.toString());
} else {
pathSB.append("->");
constructPaths(root.left, pathSB.toString(), paths);
constructPaths(root.right, pathSB.toString(), paths);
}
}
}
}
- bfs 的变形,结合额外的队列操作
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
if (root == null) return paths;
Queue<TreeNode> nodeQ = new LinkedList<>();
Queue<String> pathQ = new LinkedList<>();
nodeQ.offer(root);
pathQ.offer("" + root.val);
while (! nodeQ.isEmpty()) {
TreeNode node = nodeQ.poll();
String path = pathQ.poll();
if (node.left == null && node.right == null) paths.add(path);
else {
if (node.left != null) {
nodeQ.offer(node.left);
pathQ.offer(new String(path) + "->" + node.left.val);
}
if (node.right != null) {
nodeQ.offer(node.right);
pathQ.offer(new String(path) + "->" + node.right.val);
}
}
}
return paths;
}
}