示例:
输入:
1
/ \
2 3
\
5
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
思路:
树的dfs算法相对图的dfs算法更容易理解一点,BFS也是树比较好理解
这里先看官方给的定义
/*
Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
*/
每个节点都有他的左孩子或者右孩子,除非他是叶子节点
所以遍历就看是不是叶子节点就行了,不是叶子节点就递归,是叶子节点就记录该条路径,回溯
class Solution {public static LinkedList<String> dfs(TreeNode root, String way, LinkedList<String>path){if (root == null){return null;}else {//路径中加入该节点way += Integer.toString(root.val);// 当前节点是叶子节点if ((root.left == null) && (root.right == null))// 记录该条路径path.add(way);else {way += "->"; // 当前节点不是叶子节点,继续递归遍历dfs(root.left, way, path);dfs(root.right, way, path);}}return path;}public List<String> binaryTreePaths(TreeNode root) {LinkedList<String> path = new LinkedList();dfs(root, "", path);return path;}}
