第一种方法:递归。需要注意,原题答案需要输出 "->" ,因此需要用StringBuffer拼接。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
递归法一:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
test(root, "", res);
return res;
}
//test方法是主方法,path为拼接StringBuffer的初始值,res为最终结果
private void test(TreeNode root, String path, List<String> res) {
//当前根节点不为空时才会继续
if (root != null) {
//a为拼接字符串,先加入当前根节点的值,当前根节点需要转为String,才能放入a。
StringBuffer a = new StringBuffer(path);
a.append(Integer.toString(root.val));
//当前节点左右都为空,则为叶子结点,将a转化为String放入结果res
if (root.left == null && root.right == null) {
res.add(a.toString());
//否则不为空,需要先拼接一个 "->" ,然后递归左右子树继续遍历,属于前序遍历
}else {
a.append("->");
test(root.left,a.toString(),res);
test(root.right,a.toString(),res);
}
}
}
}
递归法二:
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) {
return res;
}
List<Integer> paths = new ArrayList<>();
traversal(root, paths, res);
return res;
}
private void traversal(TreeNode root, List<Integer> paths, List<String> res) {
paths.add(root.val);
// 叶子结点
if (root.left == null && root.right == null) {
// 输出
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.size() - 1; i++) {
sb.append(paths.get(i)).append("->");
}
sb.append(paths.get(paths.size() - 1));
res.add(sb.toString());
return;
}
if (root.left != null) {
traversal(root.left, paths, res);
//这步和后面那步的回溯刚开始没明白为什么需要,后来断点调试后知道了
//因为上面的终止条件需要用到paths的长度size和内容拼接String,因此需要递归一次就要回溯一次
paths.remove(paths.size() - 1);// 回溯
}
if (root.right != null) {
traversal(root.right, paths, res);
paths.remove(paths.size() - 1);// 回溯
}
}
}