/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new LinkedList<>();
if (root == null) {
return res;
}
helper(res, String.valueOf(root.val), root);
return res;
}
private void helper(List<String> res, String path, TreeNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
res.add(path);
return;
}
if (root.left != null) {
helper(res, path + "->" + root.left.val, root.left);
}
if (root.right != null) {
helper(res, path + "->" + root.right.val, root.right);
}
}
}
Binary Tree Paths
最新推荐文章于 2024-11-03 20:00:49 发布