给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例: 输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
package ds;
import java.util.LinkedList;
import java.util.List;
public class AllNodePath {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(6);
TreeNode node11 = new TreeNode(2);
TreeNode node12 = new TreeNode(7);
TreeNode node21 = new TreeNode(1);
TreeNode node22 = new TreeNode(5);
TreeNode node31 = new TreeNode(3);
TreeNode node42 = new TreeNode(4);
root.left = node11;
root.right = node12;
node11.left = node21;
node11.right = node22;
node22.left = node31;
node31.right = node42;
List<String> res=binaryTreePaths(root);
System.out.println(res);
}
public static List<String> binaryTreePaths(TreeNode root) {
LinkedList<String> res = new LinkedList<>();
if(root == null) return res;
solve(root, "", res);
return res;
}
public static void solve(TreeNode root, String cur, LinkedList<String> res) {
if (root == null) {
return;
}
cur += root.val;
if (root.left == null && root.right == null) {
res.add(cur);
} else {
solve(root.left, cur + "->", res);
solve(root.right, cur + "->", res);
}
}
}
第二种解决方法
package ds;
import java.util.LinkedList;
public class AllNodePath {
static LinkedList<LinkedList<String>> res=new LinkedList<>();
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(6);
TreeNode node11 = new TreeNode(2);
TreeNode node12 = new TreeNode(7);
TreeNode node21 = new TreeNode(1);
TreeNode node22 = new TreeNode(5);
TreeNode node31 = new TreeNode(3);
TreeNode node42 = new TreeNode(4);
root.left = node11;
root.right = node12;
node11.left = node21;
node11.right = node22;
node22.left = node31;
node31.right = node42;
LinkedList<Integer> ll=new LinkedList<>();
getAllPaths(root,ll);
System.out.println(res);
}
private static void getAllPaths(TreeNode root,LinkedList<Integer> ll){
if(root==null){
return ;
}
ll.add(root.val);
if(root.left==null&&root.right==null){
LinkedList temp=new LinkedList<>();
for(int i=0;i<ll.size();i++){
temp.add(ll.get(i));
}
res.add(temp);
}
getAllPaths(root.left,ll);
getAllPaths(root.right,ll);
ll.remove(ll.size()-1);
}
}