思路:
// @Title: 二叉树的所有路径 (Binary Tree Paths)
// @Author: qisiii
// @Date: 2024-09-15 16:48:02
// @Runtime: 2 ms
// @Memory: 41.4 MB
// @comment:
// @flag:
/**
* 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> result = new ArrayList<>();
doSolutin(root, result, "");
return result;
}
private void doSolutin(TreeNode node, List<String> result, String str) {
if (node == null) {
return;
}
str = str + String.valueOf(node.val) ;
if (node.left == null && node.right == null) {
result.add(str);
return;
}
str=str+"->";
doSolutin(node.left, result, str);
doSolutin(node.right, result, str);
}
}