二叉树的所有路径
解法一:递归法
import java.util.ArrayList;
import java.util.List;
public class LeetCode_257 {
private static List<String> result = new ArrayList<>();
public static List<String> binaryTreePaths(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
if (root.left == null) {
binaryTreePaths(root.right, root.val + "");
} else if (root.right == null) {
binaryTreePaths(root.left, root.val + "");
} else {
binaryTreePaths(root.right, root.val + "");
binaryTreePaths(root.left, root.val + "");
}
return result;
}
private static void binaryTreePaths(TreeNode root, String path) {
if (root == null) {
result.add(path);
return;
}
if (root.left == null && root.right == null) {
path += "->" + root.val;
result.add(path);
} else {
path += "->" + root.val;
if (root.left == null) {
binaryTreePaths(root.right, path);
} else if (root.right == null) {
binaryTreePaths(root.left, path);
} else {
binaryTreePaths(root.right, path);
binaryTreePaths(root.left, path);
}
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
for (String path : binaryTreePaths(root)) {
System.out.println(path);
}
}
}