Fetch the repository succeeded.
package LeetCode;
import java.util.ArrayList;
import java.util.List;
public class LC_257 {
public static void main(String[] args) {
}
public static List<String> binaryTreePaths(TreeNode root) {
ArrayList<String> res = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();
if (root == null) return res;
traversal(root, path, res);
return res;
}
public static void traversal(TreeNode cur, ArrayList<Integer> path, ArrayList<String> res) {
path.add(cur.val);
if (cur.left == null && cur.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size() - 1; i++) sb.append(path.get(i)).append("->");
sb.append(path.get(path.size() - 1));
res.add(sb.toString());
return;
}
if (cur.left != null) {
traversal(cur.left, path, res);
path.remove(path.size() - 1);
}
if (cur.right != null){
traversal(cur.right, path, res);
path.remove(path.size() - 1);
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。