https://leetcode.cn/problems/binary-tree-paths/
题目要求
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
递归
/**
* 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<>();
dfs(root, new StringBuilder(), res);
return res;
}
public void dfs(TreeNode root, StringBuilder str, List<String> res) {
if (root == null) return;
if (str.isEmpty()) str.append(root.val);
else str.append("->").append(root.val);
if (root.left == null && root.right == null) res.add(str.toString());
dfs(root.left, new StringBuilder(str), res);
dfs(root.right, new StringBuilder(str), res);
}
}
回溯
/**
* 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<>();
dfs(root, new ArrayList<>(), res);
return res;
}
public void dfs(TreeNode root, List<Integer> paths, List<String> res) {
paths.add(root.val);// 前序遍历,中
// 遇到叶子结点
if (root.left == null && root.right == null) {
// 输出
StringBuilder sb = new StringBuilder();// 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) { // 左
dfs(root.left, paths, res);
paths.remove(paths.size() - 1);// 回溯
}
if (root.right != null) { // 右
dfs(root.right, paths, res);
paths.remove(paths.size() - 1);// 回溯
}
}
}
思路
- 递归中使用了
new StringBuilder(str)
,实际上是每次递归传递一个新对象,避免已经访问过的结点; - 回溯中保存已经访问的结点,每一层递归结束后删除最后进入的结点。