Given a binary tree, return all root-to-leaf paths.
For example ,given the following binary tree:
1
2 3 这样的一棵树,那么它的从根到叶子节点的路径就是["1 -> 2 -> 5","1 -> 3"]。
5
那么这道题其实是考虑到用深度优先遍历算法来完成。首先考虑用递归的思想,这个思想其实很简单,但是有时却又让人有点晕,不过仔细理解一下还是可以学到的。其实每次在迭代递归的时候,最后都返回到刚才开始递归的那个地方,所以其实我们在写代码的时候是不用考虑具体内部是怎么完成的,而只要考虑递归的过程就行了。那么代码就如下:
public class Solution
{
List<String> paths = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root)
{
if(root==null)
return paths;
String curPath="";
serachTree(root, curPath);
return paths;
}
public void serachTree(TreeNode root,String currentPath)
{
currentPath+=root.val;
if(root.left == null && root.right == null)
{
paths.add(currentPath);
//System.out.println(currentPath);
return;
}
currentPath += "->";
if(root.left!=null)
{
serachTree(root.left, currentPath); //递归之后都是回退到这句之前的,所以上面那句不能写在这个判断力,否则会导致被添加了两遍
}
if(root.right!=null)
{
//currentPath += "->";
serachTree(root.right, currentPath);
}
}
}
上述代码中的//部分说明了递归的这个问题,当一次递归结束时候,都是返回到原来开始递归的位置。所以,针对此题,我的currentPath += "->"必须要写在外面。