题目描述
给定一个二叉树,返回所有从根节点到叶子节点的路径。
如果当前节点为空,直接返回
如果是叶子节点(即左右子树为空),则说明找到一条路径,则将其加入到res中
如果不是叶子节点,则继续分别遍历其左右子节点
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
dfs(root,"",res);
return res;
}
void dfs(TreeNode root,String path,List<String> res){
if(root == null){
return;
}
if(root.left == null && root.right == null){
res.add(path+root.val);
return;
}
dfs(root.left,path+root.val+"->",res);
dfs(root.right,path+root.val+"->",res);
}
}