代码:
/** * 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> list = new ArrayList<>(); if(root == null) return list; String s = ""; addTreePath(root, root.val, s, list); return list; } public void addTreePath(TreeNode root, int val, String s, List<String> list){ if(root.left == null && root.right == null){ list.add(s+root.val); } else if(root.left != null && root.right == null){ addTreePath(root.left, val, s+root.val+"->", list); } else if(root.left == null && root.right != null){ addTreePath(root.right, val, s+root.val+"->", list); } else{ addTreePath(root.left, val, s+root.val+"->", list); addTreePath(root.right, val, s+root.val+"->", list); } } }
时间: 2024-11-03 22:07:05