257. 二叉树的所有路径
难度:简单
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
解答:
/**
* 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 {
//DFS
//时间复杂度:O(N2)。空间复杂度:O(N2)
public List<String> binaryTreePaths(TreeNode root) {
List<String> ansPaths = new ArrayList<>();
DFS(root, "", ansPaths);
return ansPaths;
}
public void DFS(TreeNode root, String path, List<String> ansPaths){
if(root != null){
StringBuilder pathStr = new StringBuilder(path);
pathStr.append(root.val);
if(root.left == null && root.right == null){
ansPaths.add(pathStr.toString());
}else{
pathStr.append("->");
DFS(root.left, pathStr.toString(), ansPaths);
DFS(root.right, pathStr.toString(), ansPaths);
}
}
}
}
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。