ð 257. äºåæ çææè·¯åŸ
2022幎10æ10æ¥
- algorithm
ð 257. äºåæ çææè·¯åŸ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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 {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
// æè·¯ïŒ
// å溯
LinkedList<Integer> path = new LinkedList<>();
mySol(root, path);
return res;
}
private void mySol(TreeNode root, LinkedList<Integer> path) {
// éåœç»æ¢æ¡ä»¶
if(root.left == null && root.right == null) {
path.addLast(root.val);
getStr(path);
path.removeLast();
return;
}
path.addLast(root.val);
if(root.left != null) {
mySol(root.left, path);
}
if(root.right != null) {
mySol(root.right, path);
}
path.removeLast();
}
private void getStr(LinkedList<Integer> path) {
StringBuilder sb = new StringBuilder();
int len = path.size();
for(int i = 0; i < len; i ++) {
sb.append(path.get(i));
if(i < len - 1) {
sb.append("->");
}
}
res.add(sb.toString());
}
}