257-Binary-Tree-Paths
0x0 题目详情
1
/ \
2 3
\
50x1 解题思路
0x2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> result;
StringBuilder sb;
public List<String> binaryTreePaths(TreeNode root) {
result=new ArrayList<>();
if(root==null){
return result;
}
sb=new StringBuilder();
recur(root);
return result;
}
private void recur(TreeNode root){
if(root.left==null && root.right==null){
sb.append(root.val);
result.add(sb.toString());
int len=String.valueOf(root.val).length();
sb.delete(sb.length()-len,sb.length());
return;
}
sb.append(root.val).append('-').append('>');
if(root.left!=null){
recur(root.left);
}
if(root.right!=null){
recur(root.right);
}
int len=String.valueOf(root.val).length();
sb.delete(sb.length()-len-2,sb.length());
}
}课后总结
Last updated