给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/
2 3
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
BuildPaths(root, "", paths);
return paths;
}
public void BuildPaths(TreeNode t, String path, List<String> paths){ //paths是一个List集合,所以不能用ArrayList
if(t == null){
return;
}
StringBuffer sb = new StringBuffer(path); //暂时存在sb里
sb.append(Integer.toString(t.val)); //先序遍历
if(t.left == null && t.right == null){ //遇到叶节点的时候把sb里的字符串全传入paths中
paths.add(sb.toString());
}else{
sb.append("->"); //否则,sb加上->,然后往左右子树递归
BuildPaths(t.left,sb.toString(),paths); //注意中间的字符串应该是sb中的字符串
BuildPaths(t.right,sb.toString(),paths);
}
}
}