二叉树的所有路径
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
我一开始的错误想法
一开始用回溯,String没作为参数进行传递
总有点错误
正确解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<String> list = new ArrayList();
//String string = new String();
public void getRoute(TreeNode root,String string)
{
if(root == null)
return;
if(root.left == null && root.right == null)
{
string = string + root.val;
list.add(string);
}
else
{
string = string + root.val;
string = string + "->";
}
getRoute(root.left,string);
getRoute(root.right,string);
return;
}
public List<String> binaryTreePaths(TreeNode root) {
if(root == null)
return list;
if(root.left==null && root.right == null)
{
list.add(root.val+"");
return list;
}
getRoute(root,"");
return list;
}
}