#给定一个二叉树,返回所有从根结点到叶子节点的路径
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;
root11.left= node21;
root11.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;
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);
}
}
}
|