题目地址:
https://leetcode.com/problems/binary-tree-paths/
返回所有从根到树叶的路径。
法1:分治法。先求左子树根到叶子节点所有路径,再求右子树根到叶子节点所有路径,最后再把根节点连上去。代码如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
// 特判一下空树
if (root == null) {
return res;
}
// 如果到了叶子了,就把值加入res
if (root.left == null && root.right == null) {
res.add(Integer.toString(root.val));
return res;
}
// 分别把左右子树根到叶子节点的路径统计出来,
// 再把根节点加上去最后返回
List<String> leftPaths = binaryTreePaths(root.left);
for (String leftPath : leftPaths) {
res.add(root.val + "->" + leftPath);
}
List<String> rightPaths = binaryTreePaths(root.right);
for (String rightPath : rightPaths) {
res.add(root.val + "->" + rightPath);
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。这里忽略了字符串的copy的时间。
法2:DFS。
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
// 特判一下空树
if (root == null) {
return res;
}
dfs(root, Integer.toString(root.val), res);
return res;
}
// cur表示当前走到了的节点,path表示走到当前节点的时候的路径
private void dfs(TreeNode cur, String path, List<String> res) {
// 如果走到了null,就什么都不做,终止
if (cur == null) {
return;
}
// 如果走到了叶子,说明当前path已经包含了一条完整路径,就将其加入res
if (cur.left == null && cur.right == null) {
res.add(path);
return;
}
// 如果左子树不为空,就向左走一步,并将左子树根加入path
if (cur.left != null) {
dfs(cur.left, path + "->" + cur.left.val, res);
}
// 同理
if (cur.right != null) {
dfs(cur.right, path + "->" + cur.right.val, res);
}
}
}
时空复杂度同上。